JQuery triggerHandler does not work while trigger

I am adding a click event for a flag that will show / hide additional fields depending on its checked state. I want the handler to start loading in order to customize the initial page structure. For some reason, triggerHandler does not work on the field. If I change it to a β€œtrigger”, the handler will start firing, but the status of the flag will also change. You see what I did wrong / why triggerHandler does not work?

$('body').on("click", "#hdimage", function(){ console.log('hd'); if(!$('#hdimage').is(':checked')){ $('.sd-dim').hide(); } else { $('.sd-dim').show(); } }); $('#hdimage').triggerHandler('click'); 
+7
source share
2 answers

This happens (as described in the docs) because

Events created with .triggerHandler() do not create bubbles in the DOM hierarchy ; if they are not directly processed by the target element, they do nothing.

and since you use the delegated syntax of the .on() method, which allows the body handle the click event that occurs in the #hdimage element, this event never reaches the body ..

+9
source

Your event is not associated with "#hdimage" its body binding

 $(document).ready(function(){ $('#hdimage').on("click", function(){ alert("dostuff") }); $('#hdimage').triggerHandler('click'); }); 
0
source

All Articles