I have several divs with id=”scroll_1″, “scroll_2”, “scroll_3”, etc… When any of these divs is in the center of the window, I want to use jQuery highlight and/or change the background color of whichever div is in the center of the window. Currently the background color changes once it is in the center of the screen but I am having issues changing it back to original background color once it is no longer in the center (i.e the user has scrolled down/up to another scroll_x id.
Edit the only relevant css code I have is:
[id^=scroll_]{
background-color:white;
}
Thanks for the help!
<script>
$(document).ready(function() {
var window_height = $(window).height();
var obj_height = $('#scroll_1').height(); //height of object we are scrolling past
var top = $('#replyer').offset().top + (obj_height /2); //position on screen to start highlighting #scroll_x
$(window).scroll(function() {
var scrollMiddle = $(window).scrollTop() + ((window_height/2) - (obj_height /2));
if (scrollMiddle >= top) {
var scrollPosition = $(document).scrollTop()+ ((window_height/2) - (obj_height /2)),
currentPosition = 0;
$('div[id^="scroll_"]').each(function() {//iterate over #scroll_x and only change background until another #scroll_x is in the middle of the screen
currentPosition = $(this).offset().top;
if (currentPosition >= scrollPosition) {
$(this).prev(function(){
$(this).css('background-color',"#aaa"); //change previous #scroll_x back to original background color - Not Working Currently
});
return false; // break the loop
}
$(this).css('background-color',"#ccc"); //currently changes background of #scroll_x once in middle of screen but stays highlighted when scrolling up/down to previous/next iteration of #scroll_x
});
}
});
});
</script>
Html:
<div id="replyer">
Top line before repeating divs
</div>
<div id="scroll_1">
First object to scroll over.
</div>
<div id="scroll_2">
Want to highlight div currently in the middle of screen
</div>
<div id="scroll_3">
Only div in middle of screen should be highlighted (background change)
</div>
I’m not sure if it’s exactly what you’re after, but here is a demo that will change the object that overlaps the middle of the browser to green.
Fiddle: http://jsfiddle.net/j2ULW/1/
Full source: