I have multiple divs with id="scroll_1", "scroll_2", "scroll_3", and so on. I am trying to implement a feature where when any of these divs is in the center of the window, I want to change the background color using jQuery highlight. Currently, I am able to change the background color when the div is in the center of the screen, but I am facing difficulties reverting it back to the original color once it moves out of the center (i.e., the user scrolls up or down to another scroll_x id).
Edit The only CSS code relevant to this issue that I currently have is:
[id^=scroll_] {
background-color: white;
}
Thank you for your help!
<script>
$(document).ready(function() {
var window_height = $(window).height();
var obj_height = $('#scroll_1').height(); // Height of the object we are scrolling past
var top = $('#replyer').offset().top + (obj_height / 2); // Position on the 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 the 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 the original background color - Not working currently
});
return false; // Break the loop
}
$(this).css('background-color',"#ccc"); // Currently changes the background of #scroll_x once in the middle of the 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 the div currently in the middle of the screen
</div>
<div id="scroll_3">
Only the div in the middle of the screen should be highlighted (background change)
</div>