Reputation: 69
I've been having a lot of fun with parallax effects and various types of fading and resizing animations using the the scroll event listener, kinda like this:
window.addEventListener('scroll', function() {
var i = window.pageYOffset;
var w = window.innerWidth;
var h = window.innerHeight;
//a bunch of various functions
//making things move on the page
});
All of the things I have happening pretty much rely on tracking those three values, and what I've had to do with each function the scroll event calls is redeclare those variables within the function. I understand why (sorta, just don't ask me to explain it right now :P ) but I'm wondering if there's a way to rewrite the code so those variables need only be declared once and the different functions would be able to have access to that data without needing to tell the function to update itself... That makes sense, right?
EDIT: To be more specific as to how I currently have this set up:
function someFunction() {
var i = window.pageYOffset;
var w = window.innerWidth;
var h = window.innerHeight;
//things happen
}
function someOtherFunction() {
var i = window.pageYOffset;
var w = window.innerWidth;
var h = window.innerHeight;
//more things happen
}
window.addEventListener('scroll', function() {
var i = window.pageYOffset;
var w = window.innerWidth;
var h = window.innerHeight;
someFunction();
someOtherFunction();
});
When I began adding all these events, I did initially have the all the things that the functions do within the event listener function, in which case I didn't need to redeclare anything, but then I got to the point where I was adding @media
queries and everything broke. The best fix I came up with was a series of if
/else if
statements to change the behavior of the scrolling functions based on screen size. This rendered the whole of the processes EXTREMELY repetitive, thus, I now have the above code. In this instance, I get an 'Unreferenced' error because i
, w
, and h
are declared outside the scope of the functions being called by the event listener.
Note: I just tried--probably for like the fourth time, but I'm all for triple- and quadruple-checking--putting those variables at the top, outside of everything and that doesn't work either. It only works if I redeclare the variables for every instance they need to be used.
Upvotes: 1
Views: 1086
Reputation: 17361
Move the variables declarations outside the function to make them global. Otherwise, you can only access them within the function you declared them in.
// variables global now -- yay
// declaring variables here means that they exist past the scroll event handler
var i, w, h;
function someFunction() {
//things work
}
function someOtherFunction() {
//more things work
}
window.addEventListener('scroll', function() {
i = window.pageYOffset;
w = window.innerWidth;
h = window.innerHeight;
someFunction();
someOtherFunction();
});
Upvotes: 1