views:

47

answers:

2

In javascript, let say I got two nodes(node A, node B). when I click on node A, can I transfer "click" event to node B, so event handler for node B will execute.

+1  A: 

Yes.

document.getElementById("nodeA").onclick = function () {
  document.getElementById("nodeB").onclick();
};

Or with jQuery:

$('#nodeA').bind('click', function () {
  $('#nodeB').trigger('click');
});
Matt
@Matt: you're first example will only work with events that have been attached via the `onclick` attribute/property of an element. It won't work for events attached via `addEventListener` or `attachEvent`. Also, an `event` object won't be created because all you're doing is calling the function that is set to the property.
Andy E
@Andy: Oops. Best not use that method then :P
Matt
@Matt: +1 for the jQuery solution anyway :-)
Andy E
+3  A: 

Triggering a click event is fairly easy on buttons and other input elements, they have a click() method:

elementA.onclick = function () { elementB.click(); }

It's slightly more complicated with other events or elements that don't support the click method, you need to trigger the event using fireEvent or dispatchEvent, depending on the browser:

elementA.onclick = function () {
    var elementB = document.getElementById("elementB");
    if ("dispatchEvent" in elementB) {
        var evt = document.createEvent("MouseEvents");
        evt.initMouseEvent("click", true, true, window,
            0, 0, 0, 0, 0, false, false, false, false, 0, null);
        elementB.dispatchEvent(evt);
    }
    else if ("fireEvent" in elementB)
        elementB.fireEvent("onclick");
}
Andy E