0

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!

Ram
  • 143,282
  • 16
  • 168
  • 197
brian wilson
  • 497
  • 1
  • 7
  • 15

2 Answers2

2

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');
});
doublesharp
  • 26,888
  • 6
  • 52
  • 73
  • 1
    If you read the `.load()` doco that you linked to you'll see that there is also a [`.load()` event handler](http://api.jquery.com/load-event/) - jQuery decides which processing to do based on what arguments are passed. – nnnnnn Oct 26 '12 at 03:50
  • i have also tried this before posting the question, nothing seems to work. does it matter that the object i'm trying to simulate the click on is a textarea? – brian wilson Oct 26 '12 at 03:54
  • man if you have define a trigger first you have to define click function on that div. Like This: `$(document).ready( function() { $('#hellothere').click(function() { // some functions here }); // and now if you want to trigger the click $('#hellothere').trigger('click'); });` Now as the DOM is loaded the functions you define in click function will automatically run.. – Heart Oct 26 '12 at 04:02
0

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/

Community
  • 1
  • 1
Vivek S
  • 5,384
  • 8
  • 51
  • 72