Phillip Senn
Phillip Senn

Reputation: 47663

Getting a function to execute when a page loads

I have:

$(window).resize(function() {
    var X = $(window).height();
    $('#windowheight').text(X);
});

I'd like for it to also run when the page loads.
I thought I could do that using () at the end of the definition.

Upvotes: 0

Views: 62

Answers (3)

chaos
chaos

Reputation: 124365

$(function() {
    $(window).trigger('resize');
});

In this, we're passing a function to the jQuery object, which understands by this that we want it to run when the page is loaded and ready. The slightly more verbose and archaic way to do this is to pass the function to $(document).ready().

Upvotes: 0

Karolis
Karolis

Reputation: 9582

$(document).ready(function() {
    $(window).trigger('resize');
});

By the way you can't use () at the end of the definition as you expected because resize (in your sample) is a method call (not a definition).

Upvotes: 3

genesis
genesis

Reputation: 50982

$(document).ready(function(){
    $(window).resize(function() {
        var X = $(window).height();
        $('#windowheight').text(X);
    });

});

or

$(function(){
    $(window).resize(function() {
        var X = $(window).height();
        $('#windowheight').text(X);
    });
});

both works

Upvotes: 0

Related Questions