jQuery has its own event registration system, which is separate from the DOM's event registration. When we call $(something).click()
, all registered jQuery handlers and the registered onclick
handler will fire, but nothing else would. For example,
document.body.addEventListener('click', function() { alert('event') }, false);
document.body.onclick = function() { alert('onclick'); };
$('body').click(); // alerts "onclick"
If you call document.body.onclick()
, then only the second event will fire and alert "onclick". To get both events to fire, create an event object and dispatch it for the element in question - body in this case. You can find an example here. Unsurprisingly, IE uses a different mechanism to do the same and you need to call fireEvent.
Here's a non cross-browser example for modern browsers (taken from the MDC article above),
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initMouseEvent('click', true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
document.body.dispatchEvent(clickEvent);