Tuesday, 10 September 2013

JQuery If Statement using each value from an array

JQuery If Statement using each value from an array

I am writing a function that will be executed on multiple views of an
application, and each view can have up to 50 instances of the same
element: '.console'. I need to be able to perform an action every time the
viewport scrolls to each instance. I have the following code setting up
the variables:
//Create empty array with variable values, up to 50
var console = [];
//Find each instance of ".console" and populate the array with its pixel
position.
$('.console').each(function() {
console.push($(this)[0].offsetTop);
});
//Determine the current pixel position of the scroll
var scroll = $(document).scrollTop();
Those variables all work fine and dandy, but after hours of pouring over
jquery docs I can't figure the if statement out. Here is what I have that
works well for the first item in the array:
if (scroll == console[0]){
$('.container').show();
} else {
$('.container').hide();
}
However, I want it to be anytime the scroll position matches each of the
values in that array, hopefully something like this:
if (scroll == console[0-50])
Here is the full chunk as is:
$(document).on('scroll', function(){
//Create empty array with variable values, up to 50
var console = [];
//Find each instance of ".console" and populate the array with its pixel
position.
$('.console').each(function() {
console.push($(this)[0].offsetTop);
});
//Determine the current pixel position of the scroll
var scroll = $(document).scrollTop();
//Anytime the scroll matches any of the instances of console, show a div
if (scroll == console[0]){
$('.container').show();
} else {
$('.container').hide();
}
});
Any help would be appreciated. I am pretty new to Javascript/JQuery so if
I'm approaching the problem in the wrong way altogether, please let me
know. Thanks!

No comments:

Post a Comment