I have always been confused by this, I am not even sure this is possible, but here I go anyways.
If I have a function that increments a value stored in a variable, how do I get the variable outside the function?
Example, this is not great code but I am just playing around.
function scrollVal() {
var pos = 0;
$(document).scroll(function() {
pos = $(document).scrollTop();
return pos;
});
}
var scrollPos = scrollVal();
console.log(scrollPos);
I tried the above after something like this failed
var pos = 0;
$(document).scroll(function() {
pos = $(document).scrollTop();
});
console.log(pos);
I don't see how it's possible to magically update the variable. There has to be a way though. I am trying to use that variable to manipulate an element. Ex
var geometry = new FSS.Plane(1600, 835, pos, 15);
So my question is basically how can I dynamically change a number within a function, then use that outside the function so that I can manipulate an element with the changing value?
EDIT REWORD: I poorly worded this question, what I mean by it fails, is that I cannot get the value inside the scope of the function outside the scope of the function. I want to pass the incremental value as the scrolling takes place into the instance.
Imagine you scroll on a page, and as you scroll something grows, or a color changes. I think this should be easy and it makes me sound like a noob, but I've never done this and I am not sure what rules apply here, and I understand why the variable doesnt update, but I don't know the solution.
Maybe it's not possible to update the value in an instance, but first I need to get that variable to render the appropriate number in realtime, then I can find out.
A good basic example would be appending the variable to an element and watching that number grow as the page is scrolled upon. I have seen this before so I know it's possible, thats what I love about code if you can think it, most likely its possible, but this solution is not straight forward there is a caveat!!! :)
Again this could be made possible if I did something like
var window.pos = 0;
$(document).scroll(function() {
pos = $(document).scrollTop();
$('.something').html(pos);
});
Obviously this is made possible by being inside the function, but since I need to pass it to an instance I dont want to execute it over and over..