Question

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');
Était-ce utile?

La 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..

Autres conseils

Your Event is not bound to "#hdimage" its bound to 'body'

$(document).ready(function(){
    $('#hdimage').on("click", function(){
        alert("dostuff")
    });
    $('#hdimage').triggerHandler('click');
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top