event-handlingjqueryjquery-triggerhandlerjquery-trigger

jquery triggerHandler doesn't work while trigger does


I am adding a click event to a checkbox which will show/hide additional fields depending on its checked status. I want the handler to fire on load to set up the initial page structure. For some reason triggerHandler is not working on the field. If I change it to 'trigger' the handler will fire, but the checkbox status will also change. Can you see what i've done wrong/why triggerHandler won't work?

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

Solution

  • That happens (as described in the docs) because

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

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