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?

1
  • document ready or window load you mixed them... :) Commented May 31, 2012 at 20:29

7 Answers 7

8

Yes.

$(document).ready(function(){ // on document ready
    $(".results .view-rooms").click(); // click the element
})
Sign up to request clarification or add additional context in comments.

Comments

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

5 Comments

I know what DOM is lol, I was just playfully pointing out that $(document).ready() exists
@PhillipSchmidt. $(document).ready(fn) is exactly the same as $(fn), the second is an alias to the first.
hmm.. interesting - I actually didn't know that. Though it makes sense.
@PhillipSchmidt. You might want to read this if that was new to you. Disclaimer, it's my question and answer there.
well enjoy your +rep for teaching me something new (and pretty interesting, too)
3
$(document).ready(function(){ $('.results .view-rooms').click(); });

Comments

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

1 Comment

+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.
1

Put the code inside

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

like:

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

or

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

Comments

0
$(function(){

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

    }

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

}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.