Unknown developer
Unknown developer

Reputation: 5930

jQuery trigger() method

Could someone explain to me what exactly this means

trigger executes the code for the event handler but not actually executes the event itself?

Consider the following code:

$('#parent').on('click',function (event){
   console.log(event);
});

$('#parent').trigger('click');

trigger does produce an Event object since it consoles it. So, in which way it does not execute the event?

Upvotes: 3

Views: 104

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

jQuery has a rather nice event system, that handles events in a more complex way than the basic event bubbling. For instance it allows multiple events, of the same type, on an element.

That means that jQuery events sit on top of the browser events and add features. When you trigger a jQuery event it just send messages up the jQuery DOM tree, which causes things to respond, but it does not necessarily generate the native browser events.

You can still hit the native event generation by using the underlying DOM elements and methods that jQuery wraps:

// This will generate a click event "for jQuery to hear"
$('#parent').trigger('click');

or this does exactly the same as above:

$('#parent').click();

Whereas this will fire the native DOM click event "actually clicks the button/link":

$('#parent')[0].click();

Update (from A. Wolff):

Some jQuery click events are passed on to the native click event. An exception being anchor links (which do not). I would have to test it to see if native clicks are generated or not for buttons and other inputs.

Upvotes: 4

Related Questions