Reputation: 11749
I have a box, and I need to detect when elements are inside of it as the user scrolls the page. It also needs to be responsive.
I had it working earlier, with window height and width etc, but the percentages became all screwed up depending on which device I was on. So I instead decided to opt for using a fixed/absolute element and then somehow detect intersection/collision with other elements.
The absolute element css is
#windowBox {
position: fixed;
top: 30%;
bottom: 30%;
left: 0;
right: 0;
}
Im trying to have the elements inside of it light up when they scroll into it. And also, ideally....when the user clicks next or prev, have the next and prev elements come automatically into the box / slide up or down.
I've been at this for hours and I'm tearing my hair out. It should be so simple!
I've tried this, but it doesn't work. Well it kinda does, but not really. When I resize the window, it gets all messed up. And its also jumpy and glitchy.
Obviously for the resize thing, I need to recalculate the percentages to get it to work. But I think using that absolute element and detcting intersection is the more logical way to go for me.
var windowHeight = $(window).height(),
gridTop = windowHeight * .3,
gridBottom = windowHeight * .3,
console.log(gridTop),
console.log(gridBottom);
$(window).scroll(function() {
var t = $(this);
$('.formQuestion').each(function() {
var thisTop = $(this).offset().top - t.scrollTop();
if (thisTop > gridTop && (thisTop + $(this).height()) < gridBottom) {
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
});
});
Upvotes: 0
Views: 331
Reputation: 16855
If you don't want to use any kind of external jQuery
library...just use jQuery .offset().top
to get the collision of the divs
Stack Snippet
$(window).on("scroll", function() {
$(".item").each(function() {
if ($(this).offset().top < $(".middle-bar").offset().top + $(".middle-bar").outerHeight() && $(this).offset().top > $(".middle-bar").offset().top - $(this).outerHeight()) {
$(this).addClass("newClass");
} else {
$(this).removeClass("newClass");
}
});
});
body {
margin: 0;
}
.main {
margin: 300px 0;
}
.item {
height: 50px;
background: #ccc;
margin: 0 0 50px;
position: relative;
transition: all .5s ease;
}
.middle-bar {
position: fixed;
height: 50px;
background: black;
left: 0;
right: 0;
top: 50%;
transform: translateY(-50%);
}
.item.newClass {
background: red;
transform: scale(.8);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="middle-bar"></div>
<div class="main">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
Upvotes: 1
Reputation: 14
You should take a look at Midnight.js, that's what you're looking for i think.
Upvotes: 0