简体   繁体   中英

Make jQuery code in window load, scroll and resize only fire once?

I have code that fires on window load, scroll and resize:

jQuery(window).bind("load scroll resize", function() {
   // do stuff on every event

   // do something else only once

});

However I want one part of the code to only fire once. How can this be done?

UPDATE - I have a variable already defined in the code that re-fires that ideally id like to use in the code that doenst re-fire.

It seems like this is what you are really looking for:

jQuery(document).ready(function () {
    var foo = "bar"; //define on load
    jQuery(window).on("scroll resize", function () {
        jQuery("body").append(foo); // used on scroll/resize events
    })
})

Fiddle (you can resize the fiddle windows to see the event works using the defined variable)


If you also want the scroll/resize event to happen on initial load, you could do something like this:

jQuery(document).ready(function () {
    var foo = "bar"; //define on load
    var myFunc = function () {
        jQuery("body").append(foo); // used on scroll/resize events
    }
    myFunc();
    jQuery(window).on("scroll resize", myFunc)
})

Fiddle

Another example you can test scroll with - epilepsy warning :)

Also I used jQuery() in my example just because you did. Unless you have some kind of conflict most people prefer using the shortcut $() .


In case there is any confusion with my sample code, your above code (comments) would look like this:

jQuery(document).ready(function () {
    // do something else only once
    var myFunc = function () {
        // do stuff on every event
    }
    myFunc(); //remove this if you don't want it called on initial load
    jQuery(window).on("scroll resize", myFunc)
})

Basically in the above sample, on the initial load your function and event will get declared, initialized, and called. Then the function will get called every time the scroll and resize events take place.

var some_var = 1;

$(window).on("load scroll resize", function() {
   // do stuff on every event
});

$(window).one("load scroll resize", function() {
   // do stuff only once
});

That will execute the one part of the code only once, and the other part every time. Since some_var is declared outside of both blocks, it'll be available inside both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM