2

I have the following function which is activated on click:

$('.results .view-rooms').click(function(){   }

Is there anyway I can trigger this function on document load?

gdoron
  • 147,333
  • 58
  • 291
  • 367
user1038814
  • 9,337
  • 18
  • 65
  • 86

7 Answers7

8

Yes.

$(document).ready(function(){ // on document ready
    $(".results .view-rooms").click(); // click the element
})
Kevin B
  • 94,570
  • 16
  • 163
  • 180
4
$('.results .view-rooms').click()

You can put it in DOM ready:

$(function(){
    $('.results .view-rooms').click()
});

Or window load:

$(window).load(function(){
    $('.results .view-rooms').click();
});

Note that there is no such event document load.
We have DOM ready or window load

gdoron
  • 147,333
  • 58
  • 291
  • 367
3
$(document).ready(function(){ $('.results .view-rooms').click(); });
Pethical
  • 1,472
  • 11
  • 18
2

Considering that you're already using jQuery to bind the event handler, and assuming that code is already in a position where the entire DOM has been constructed, you can just chain the call to .click() to then trigger that event handler:

$('.results .view-rooms')
                        .click(function(){...}) //binds the event handler
                        .click(); // triggers the event handler
gdoron
  • 147,333
  • 58
  • 291
  • 367
Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
  • +1 for the chain, I'm not sure he can use it in this case, But teaching the op the chainablility of jQuery is useful. – gdoron Jun 01 '12 at 06:39
1

Put the code inside

$(function(){ // code here  }); 

like:

$(function(){ 
   $(".results .view-rooms").click(); 
});

or

$(function(){ 
   $(".results .view-rooms").trigger('click'); 
});
4b0
  • 21,981
  • 30
  • 95
  • 142
0
$(function(){

    $('.results .view-rooms').click(function(){ 

    }

    $(".results .view-rooms").trigger('click');

}
gdoron
  • 147,333
  • 58
  • 291
  • 367
Alfred Larsson
  • 1,339
  • 1
  • 9
  • 16
0

The best way is:

html form:

<form action="https://stackoverflow.com" method="get">
  <button id="watchButton"></button>
</form>

End Jquery:

<script>
   $('document').ready(function() {
     $('#watchButton').click();
   });
</script>

JQuery Version:

https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
Consule
  • 1,059
  • 12
  • 12