brian wilson
brian wilson

Reputation: 495

jquery click simulation not working

trying to use this code to simulate a click on an object, I am injecting this code in the html..

<script type='text/javascript'> 
   $(window).load(function() {
      $('#hellothere').click();
   });
</script>

Not wroking... at all!

Upvotes: 0

Views: 1164

Answers (2)

doublesharp
doublesharp

Reputation: 27609

You should use the ready() function to run code when the DOM is ready - http://api.jquery.com/ready/ - the load() method is for loading new content - http://api.jquery.com/load/ - and is incorrect for your purposes. You can then use trigger() to fire a click event on a DOM object.

// run when the DOM is loaded
$(document).ready(function(){
    $('#hellothere')
         // Set up the click event
         .on('click', function(){ alert('you clicked #hellothere'); })
         // Trigger the click event
         .trigger('click');
});

Upvotes: 2

Vivek S
Vivek S

Reputation: 5540

If you are trying to simulate a click on object, you should use the trigger method,

$(function){
   $('#hellothere').trigger('click');
});

Here is the link to docs on trigger: http://api.jquery.com/trigger/

This is the code for the click method:

jQuery.fn.click = function (data, fn) {
  if (fn == null) {
    fn = data;
    data = null;
}

return arguments.length > 0 ? this.on(name, null, data, fn) : this.trigger(name);
}

as you can see; if no arguments is parsed to the function it will trigger the click event.

So use .trigger("click") cause you will call one less function. https://stackoverflow.com/a/9666547/887539

PS:

This is a nice tool to look into jQuery's source code: http://james.padolsey.com/jquery/

Upvotes: 0

Related Questions