Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why jQuery's triggerHandler() doesn't prevent inline events?

I've made this test code for the question: https://jsfiddle.net/5phqm/1/

As far as I understand, if jQuery's triggerHandler() prevents default browser behavior, then native JavaScript events will not be triggered and handled (and it's true for addEventListener() in my code), but inline event, added through tag's attribute onclick="" will be triggered anyway! Why it happens? Am I misunderstanding something about events triggering in browser?

like image 210
Raiden Avatar asked Nov 05 '22 10:11

Raiden


1 Answers

It can be confirmed that inline handlers are run because it is explicitly coded:

handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) {
    event.preventDefault();
}

where ontype is in this case "onclick". So it is fetching the onclick property of the element and then executing it. This piece of code is always called, regardless of .trigger/.triggerHandler.

Native actions however, like elem.click(), are only executed inside an if block:

if ( !onlyHandlers && !event.isDefaultPrevented() ) {
    // ...
    elem[ type ]();

where onlyHandlers is true for triggerHandle and false for .trigger, and therefore triggerHandler does not execute e.g. elem.click() (whereas .trigger does). As such, the native action is prevented.

So inline handlers and native actions are separate things and are also handled separately. Only native actions are prevented by .triggerHandler.

like image 101
pimvdb Avatar answered Nov 14 '22 23:11

pimvdb