SOLUTION
$(window).scroll(function() {
var y = $(this).scrollTop();
for (var i = 0; i < offset.length; i++)
{
if (y < offset[i].bottom) {
$("#catSelect option:selected").removeAttr("selected");
$("#catSelect option[value=#"+offset[i].id+"]").attr("selected", "selected");
break;
}
}
});
Thank you for your help guys!
PROBLEM
I am a beginner at JavaScript and jQuery, so I hope some kind soul can help me out. Below is a snippet of a code that executes just fine... but as it is pretty repetitive, I am trying to come up with some code to help me 'automate' all these conditions within the switch statement instead of manually specifying it (if that makes sense). I'm going with a 'for' loop but no results as of yet.
A nudge in the right direction, please? Thank you :)
~ preliminary code ~
var offset = [];
$(".cat").each(function() {
var top = $(this).offset().top;
var bottom = top + $(this).outerHeight();
var id = $(this).attr("id");
offset.push({"top": top, "bottom": bottom, "id": id });
$(document.body).append(offset.length);
});
~ the code it's all about ~
$(window).scroll(function() {
var y = $(this).scrollTop();
switch (true) {
case (y < offset[0].bottom):
$("#catSelect option:selected").removeAttr("selected");
$("#catSelect option[value=#"+offset[0].id+"]").attr("selected", "selected");
break;
case (y < offset[1].bottom):
$("#catSelect option:selected").removeAttr("selected");
$("#catSelect option[value=#"+offset[1].id+"]").attr("selected", "selected");
break;
case (y < offset[2].bottom):
$("#catSelect option:selected").removeAttr("selected");
$("#catSelect option[value=#"+offset[2].id+"]").attr("selected", "selected");
break;
}
});