Skip to content Skip to sidebar Skip to footer

JQuery Click Event When Triggered Programatically

I have a link with an inline onclick event: click I registered an additional function on the onclick event: jQuery('#addMoreO

Solution 1:

I am pretty sure this is caused by the order of things happening.

If you look at this live example you'll see everything works as expected. This is because the event is registered, and then called. The code looks like:

jQuery(document).ready(function(){   

    jQuery("#addMoreOptions").live('click',function(){
        console.log('clicked');
    });

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

});

function somefunction()
{
 alert("clicked");   
}

When the page loads, you get an alert and a console.log.

Now with the very small change of putting the $('#addMoreOptions').click(); before registering the event as in this live example you only get the alert from the inline function.

For reference the code is

jQuery(document).ready(function(){   
     $('#addMoreOptions').click();  

    jQuery("#addMoreOptions").live('click',function(){
        console.log('clicked');
    });   

});

function somefunction()
{
 alert("clicked");   
}

Solution 2:

An alternative way of triggering a click event would be to use the .trigger() function:

jQuery('#addMoreOptions').trigger('click');

Post a Comment for "JQuery Click Event When Triggered Programatically"