35

Out of curiosity -- what is the purpose of / use cases for jQuery's triggerHandler? As far as I can tell, the only "real" differences between trigger and triggerHandler is whether or not the native event fires, and event bubbling behavior (though triggerHandler's bubbling behavior doesn't seem hard to replicate with trigger in a few more lines of code). What is the advantage to ensuring the native event does not fire?

I'm curious if this is a convenience function or there's a deeper reason it exists, and what why/when I would use it.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
David Eads
  • 1,502
  • 1
  • 11
  • 21

4 Answers4

70

From the Docs at http://api.jquery.com/triggerHandler/

The .triggerHandler() method behaves similarly to .trigger(), with the following exceptions:

  • The .triggerHandler() method does not cause the default behavior of an event to occur (such as a form submission).

Not preventing the default browser actions allow you to specify an action that occurs on focus or select, etc etc etc, that applies a style. Maybe you have a dynamic menu that is Javascript based, so you don't want to apply the style purely with CSS otherwise those with Javascript disabled won't understand why the layout looks odd. You can use something like $('menu1select').triggerHandler('click');

  • While .trigger() will operate on all elements matched by the jQuery object, .triggerHandler() only affects the first matched element.

If you have an event which hides an element onclick for example, and you want to call that function generally, instead of having to specify each element, you can use $('.menu').triggerHandler('click');

  • Events created with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.

Prevents propagation, hopyfully don't have to explain this one...

  • Instead of returning the jQuery object (to allow chaining), .triggerHandler() returns whatever value was returned by the last handler it caused to be executed. If no handlers are triggered, it returns undefined

This one should be self explanatory as well...

Robert
  • 21,110
  • 9
  • 55
  • 65
  • The docs are why I asked the question in the first place. I understand the behavior, but I'm curious if this is a convenience function or there's a deeper reason it exists. – David Eads Sep 22 '10 at 18:59
  • 1
    You seriously downvoted because you don't understand the examples given in the docs. Alright, let me spell it out for you then. – Robert Sep 22 '10 at 19:08
  • 6
    You don't have to upvote, you can just not vote at all... I gave you more examples and you still don't understand, which isn't my fault. In some cases you don't want to return false on an actual click, so #1 is valid. #2 Yeah... that's the point, hiding only one, but calling the entire matching array. So you can setInterval that function to increment hiding #3 See #1, with the idea of you wanting different actions based on actual click vs simulated. #4 If you want the value returned by the last actual event without creating a new one. – Robert Sep 22 '10 at 20:58
  • 1
    @DavidEads: why don't you accept this one? I rejected the upvote on your question (and upvoted only Robert's answer), because I see you downvoted this answer earlier instead of asking first. I think you should accept this post, as this answers your question. And after that, you could get an upvote to your question too (at least from me). :) – Sk8erPeter Jan 28 '13 at 19:34
  • 2
    This is a great answer to the question. I don't see why it hasn't been accepted. – Hovis Biddle Mar 11 '13 at 16:56
4

What is the advantage to ensuring the native event does not fire?

  • You have actions bound to a 'focus' event but you don't want the browser to focus really focus it (might seem dumb but it could happen, couldn't it? like a code that you would like to execute once without losing the current focus).

  • A component that you are making want to trigger 'load' (just an example of a generic thing) of another component that is inside it.

    In that case, if you are calling 'load' of children when 'load' of the parent comes, you don't want to do this because it would cause an infinite call if the event.stopPropagation isn't called by the listeners of 'load' event (caused by bubling):

$container.on('load', function () {
    $somethingInsideContainer.trigger('load'); 
    // Would cause a loop if no event.stopPropagation() is called
});

In that case you have to call triggerHandler().

Micaël Félix
  • 2,697
  • 5
  • 34
  • 46
3

Difference 1: you can call all elements matched by the JQuery object using trigger.

//Example1 for trigger. All 3 button click events are fired when used trigger. //Try Replacing trigger method with triggerHandler(). You will see only the first button element event handler will fire .

<button id = "button1">button1</button>
<button id = "button2">button2</button>
<button id = "button3">button3</button>

$("#button1").on("click", function(){
alert("button1 clicked");
});
$("#button2").on("click", function(){
alert("button2 clicked");
});
$("#button3").on("click", function(){
alert("button3 clicked");
});

//substitute trigger with triggerHandler to see the difference

$("#button1, #button2, #button3").trigger("click");

Difference 2: when using triggerHandler() for an element event, the native event will not be called for that element. trigger() will work fine.

//Example:

//substitute trigger with triggerHandler to see the difference

 <button id = "button1">button1</button>
  <button id = "button2">button2</button>

$("#button1").on("click", function(){
 $("#button2").trigger('click');

});

$("#button3").on("click", function(){
var value = $("#button2").triggerHandler('click');
    alert('my value:'+ value)
});

$("#button2").on('click', function(){
alert("button2 clicked");

});

Difference 3: trigger() return Jquery object whereas triggerHandler() return the last handle value or If no handlers are triggered, it returns undefined

//Example3

<button id="button1">Button1</button>
<button id="button2">Button2</button>
<button id="button3">Button3</button>


$("#button1").on("click", function(){
var myValue = $("#button2").trigger('click');
    alert(myValue);
});

$("#button3").on("click", function(){
var value = $("#button2").triggerHandler('click');
    alert('my value:'+ value)
});

$("#button2").on('click', function(){
alert("button2 clicked");
    return true;
});

Other difference is

Events triggered with triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.

maxspan
  • 13,326
  • 15
  • 75
  • 104
3

For me the main difference is that 'triggerHandler' returns whatever was returned by the last handler, whereas 'trigger' returns the jQuery object.

So, for a handler such as:

  $( document ).on( 'testevent', function ()
  {
    return false;
  });

Using 'triggerHandler' you can do the following:

  if( $( document ).triggerHandler( 'testevent' ) === false )
  {
    return;
  }

So you would use 'triggerHandler' if you wanted to respond to the result returned from the handler.

Steve Roberts
  • 2,701
  • 1
  • 15
  • 9