JSFiddle - React, Tailwind, and code Playground
by GMK Hussain
HTML
<div id="scroll_1">
<h1>My Heading 1</h1>
First object to scroll over.
</div>
<div id="scroll_2">
<h1>My Heading 2</h1> Want to highlight div currently in the middle of screen
</div>
<div id="scroll_3">
<h1>My Heading 3</h1>
Only div in middle of screen should be highlighted (background change)
</div>
CSS
body {
background: #fff;
}
[id^=scroll_]{
background-color:#eee;
padding:10px;
height:300px;
margin:30px 0;
}
.activediv{
background: #369;
box-shadow: 0 0 10px #ccc;
color:#fff;
}
.activediv {
padding-left: 100px;
transition: all 500ms;
}
JavaScript
$(document).ready(function() {
var window_height = $(window).height();
$(window).scroll(function() {
var scrollMiddle = $(window).scrollTop() + (window_height/2);
$('div[id^="scroll_"]').each(function() {
elTop = $(this).offset().top;
elBtm = elTop + $(this).height();
if (elTop < scrollMiddle && elBtm > scrollMiddle) {
$(this).addClass("activediv");
} else {
$(this).removeClass("activediv");
}
});
});
});