Reputation: 23613
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.
Upvotes: 1
Views: 5499
Reputation: 19086
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)
})
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.
Upvotes: 3
Reputation: 8376
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.
Upvotes: 2