How to detect a div box on scroll - javascript

I want to positioned a div box fixed every time I scroll down the page as touch that box and keep scrolling down so that it never disappears after a user sees it.
$(window).scroll(function() {
if($('section#top_casino_offer').scrollTop() +
$('section#top_casino_offer').innerHeight() >= $('section#top_casino_offer')[0].scrollHeight) {
console.log('show');
} else {
console.log('hide');
}
});
I made a quick snippet for it here
I tried the code above but it does not work.

you could specify a scrolling value like this, Check the following snippet :
$(window).scroll(function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 90;
// set to whatever you want it to be
if(y_scroll_pos > scroll_pos_test) {
$("#top_casino_offer").css("position","fixed");
}
else
{
$("#top_casino_offer").css("position","relative");
}
});
.outer{
height: 1100px;
background: green;
width: 100%;
}
#yellow{background: yellow;
}
#top_casino_offer {
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
<p>Paragraph</p>
<section id="yellow">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut doloremque repellendus eligendi, dolorem vel sapiente harum repellat voluptatum hic, officiis perspiciatis dolor labore maiores cumque eos necessitatibus non ex, fuga.</p>
</section>
<section id="top_casino_offer">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut doloremque repellendus eligendi, dolorem vel sapiente harum repellat voluptatum hic, officiis perspiciatis dolor labore maiores cumque eos necessitatibus non ex, fuga.</p>
</section>
</div>
hope this helps :)

Related

Question: Intersection Observer - Animation

I spent the weekend trying to get my head around the Intersection Observer Animation for an animation that I'm trying to achieve. From my understanding of the intersection observer my code should work as I intended but the reality is it doesn't 🥲
My goal is that the scroll animation starts when the element reaches a certain point within the viewport. In my codepen, I've marked the point where the animation should start with a border. However, the animation starts as soon as the div enters the viewport.
Also, when the element gets below the border again, the animation should stop.
I would very much appreciate any help to achieve my goal.
Code example: https://codepen.io/aki-sol/pen/RwJPJrW?editors=1111
Also, if you have any feedback on my animation approach I'm very happy to receive criticism/ better way of approaching this.
<div class="text">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Expedita provident unde, sequi aliquid porro ipsa vitae nulla dolor neque aliquam quisquam nam magnam architecto, consequuntur est in beatae, nihil optio.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et, architecto eveniet assumenda praesentium in laboriosam vitae atque, sunt minima aliquid quam distinctio voluptatum commodi veniam iure officia provident voluptas ea?
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eveniet quo commodi laborum perspiciatis nemo voluptates quod odio quis necessitatibus perferendis? Ipsum, quasi nesciunt. Debitis omnis consequuntur laboriosam veniam, non impedit!
</div>
<div class="box">
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
</div>
<div class="text">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Expedita provident unde, sequi aliquid porro ipsa vitae nulla dolor neque aliquam quisquam nam magnam architecto, consequuntur est in beatae, nihil optio.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et, architecto eveniet assumenda praesentium in laboriosam vitae atque, sunt minima aliquid quam distinctio voluptatum commodi veniam iure officia provident voluptas ea?
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eveniet quo commodi laborum perspiciatis nemo voluptates quod odio quis necessitatibus perferendis? Ipsum, quasi nesciunt. Debitis omnis consequuntur laboriosam veniam, non impedit!
</div>
body {
position: relatvie;
heig;
}
body:after {
content: '';
position: fixed;
bottom: 40%;
height: 1px;
width: 100%;
border-bottom: 1px solid blue;
}
.text {
background-color: brown;
color: white;
height: 150vh;
}
.box {
display: flex;
position: relative;
}
.box-content {
width: 200px;
height: 200px;
background-color: greenyellow;
margin-right: 50px;
}
const boxElement = document.querySelector(".box");
//this function calls the aniamtion function and observes the window scroll position
function getWindowScrollPos() {
let windowPosition = window.scrollY;
window.addEventListener("scroll", () => {
windowPosition = window.scrollY;
animateBox(boxElement, windowPosition);
});
}
function animateBox(box, scrollPosition) {
let boxOffsetPosition = scrollPosition;
box.style.left = `${-boxOffsetPosition}px `;
}
function boxObserver(element) {
const observer = new IntersectionObserver(
(entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
getWindowScrollPos();
}
});
},
{ rootMargin: "0% 0% 60% 0%" }
);
observer.observe(element);
}
boxObserver(boxElement);
Thanks a lot!
There are two things to note here, I guess.
First, the Intersection Observer (along with Resize Observer) is not the best thing to test in online sandboxes, because they run code in an iframe, which leads to such a behavior. You should try to run your code in a browser.
There are questions related to this problem. E.g.: In codepen, Intersection observer has different behavior from browser window
Second, you're probably misunderstanding rootMargin. You set it to 0% 0% 60% 0% which means “add 60% of the height of the root to the very root, and use it as a bottom border for intersection”.
What you actually want to is to decrease the bottom border, not to increase. So, just set it to 0% 0% -40% 0% and it will work.
The Intersection Observer tutorial that helped me a bit to understand the rootMargin weirdness. Maybe it will be useful for you too.
Demo
Here's your snippet that I changed a bit to make it work inside an iframe. I've added a container node and use it instead of window.
const boxElement = document.querySelector('.box');
const container = document.getElementById('container');
function setupListener() {
let scrollPosition = container.scrollTop;
animateBox(boxElement, scrollPosition);
container.addEventListener('scroll', () => {
scrollPosition = container.scrollTop;
animateBox(boxElement, scrollPosition);
});
}
function animateBox(box, scrollPosition) {
let boxOffsetPosition = scrollPosition;
box.style.left = `${-boxOffsetPosition}px`;
}
function boxObserver(element) {
const observer = new IntersectionObserver(
(entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setupListener();
}
});
},
{
root: document.getElementById('container'),
rootMargin: `0px 0px -40% 0px`
}
);
observer.observe(element);
}
boxObserver(boxElement);
body {
margin: 0;
overflow: hidden;
}
body:after {
content: "";
position: fixed;
bottom: 40%;
height: 1px;
width: 100%;
border-bottom: 1px solid blue;
}
.container {
overflow: scroll;
max-height: 100vh;
}
.text {
background-color: brown;
color: white;
height: 150vh;
}
.box {
display: flex;
position: relative;
}
.box-content {
width: 200px;
height: 200px;
background-color: greenyellow;
margin-right: 50px;
}
<div class="container" id="container">
<div class="text">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Expedita provident unde, sequi aliquid porro ipsa vitae nulla dolor neque aliquam quisquam nam magnam architecto, consequuntur est in beatae, nihil optio.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et, architecto eveniet assumenda praesentium in laboriosam vitae atque, sunt minima aliquid quam distinctio voluptatum commodi veniam iure officia provident voluptas ea?
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eveniet quo commodi laborum perspiciatis nemo voluptates quod odio quis necessitatibus perferendis? Ipsum, quasi nesciunt. Debitis omnis consequuntur laboriosam veniam, non impedit!
</div>
<div class="box">
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
</div>
<div class="text">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Expedita provident unde, sequi aliquid porro ipsa vitae nulla dolor neque aliquam quisquam nam magnam architecto, consequuntur est in beatae, nihil optio.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et, architecto eveniet assumenda praesentium in laboriosam vitae atque, sunt minima aliquid quam distinctio voluptatum commodi veniam iure officia provident voluptas ea?
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eveniet quo commodi laborum perspiciatis nemo voluptates quod odio quis necessitatibus perferendis? Ipsum, quasi nesciunt. Debitis omnis consequuntur laboriosam veniam, non impedit!
</div>
</div>
What may be improved
Also, if you have any feedback on my animation approach I'm very happy to receive criticism/ better way of approaching this.
Well, you surely should think about the scroll listener you will have after the intersection started. If you don't remove it, it will hang. Or even worse, they will be increasing during each intersection. Not a good thing.
Also it's better to animate transform, not left. It's good for optimization. Otherwise you'll get junky animation which will freeze the whole site. Check this set of articles by Google: web.dev/animations/.

How to go down to different sections in the same page and go all the way up using buttons?

I am fairly new to javascript. I am stuck on this code.
I'm trying to create a button to navigate between top and bottom of a web page. Initially, the scroll to bottom works, but once I click on the back to top button, the scroll down logic breaks. I'm unable to figure out where I'm applying the incorrect logic. Thanks in advance
https://jsfiddle.net/riodahamster/9vtxh0aL/9/
var i = 1;
$(".scroll-top").click(function() {
$("html, body").animate({
scrollTop: 0
}, "slow");
window.icount = 0;
});
var icount = 0
$('.down-btn').on('click', function(e) {
e.preventDefault();
window.icount++;
var offset = $("div.next-section").eq(icount).offset().top;
$('html, body').stop().animate({
scrollTop: offset
}, 400);
});
You can Scroll Into an element using vanilla JavaScript. Just follow the tricks.
The scrollIntoView scroll the page to view the element. For that purpose here I've created two empty elements #top-view and #bottom-view at the top and the bottom of the HTML respectively.
After that when you click on Go Bottom and Go Up buttons then it brings you to the #bottom-view and #top-view elements.
const bottomBtn = document.querySelector('#go-bottom');
const upBtn = document.querySelector('#go-up');
const topView = document.querySelector('#top-view');
const bottomView = document.querySelector('#bottom-view');
bottomBtn.addEventListener('click', (evt) => {
evt.preventDefault();
bottomView.scrollIntoView({behavior: 'smooth'});
});
upBtn.addEventListener('click', (evt) => {
evt.preventDefault();
topView.scrollIntoView({behavior: 'smooth'});
});
#page-1 {
background: yellow;
color: #222;
}
#page-2 {
background: red;
color: #fff;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!-- empty element for scrolling into it -->
<div id="top-view"></div>
<button id="go-bottom">Go Bottom</button>
<section id="page-1">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Autem esse cupiditate unde magni facilis, quod saepe ad eligendi tenetur voluptas ea maxime dolorem id explicabo incidunt tempora quae debitis soluta!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Magni, voluptatum aspernatur aut explicabo dignissimos aperiam, ut exercitationem labore? Hic necessitatibus nostrum delectus suscipit nihil eveniet asperiores alias facere a quod.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Autem esse cupiditate unde magni facilis, quod saepe ad eligendi tenetur voluptas ea maxime dolorem id explicabo incidunt tempora quae debitis soluta!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Magni, voluptatum aspernatur aut explicabo dignissimos aperiam, ut exercitationem labore? Hic necessitatibus nostrum delectus suscipit nihil eveniet asperiores alias facere a quod.
</p>
</section>
<section id="page-2">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Autem esse cupiditate unde magni facilis, quod saepe ad eligendi tenetur voluptas ea maxime dolorem id explicabo incidunt tempora quae debitis soluta!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Magni, voluptatum aspernatur aut explicabo dignissimos aperiam, ut exercitationem labore? Hic necessitatibus nostrum delectus suscipit nihil eveniet asperiores alias facere a quod.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Autem esse cupiditate unde magni facilis, quod saepe ad eligendi tenetur voluptas ea maxime dolorem id explicabo incidunt tempora quae debitis soluta!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Magni, voluptatum aspernatur aut explicabo dignissimos aperiam, ut exercitationem labore? Hic necessitatibus nostrum delectus suscipit nihil eveniet asperiores alias facere a quod.
</p>
</section>
<button id="go-up">Go Up</button>
<!-- empty element for scrolling into it -->
<div id="bottom-view"></div>
</body>
</html>
The code works fine. The issue is you havent added Jquery!
Also you have to target the bottom div to get the down function to move you to the bottom of the page. In this case, yello class div!
var i = 1;
$(".scroll-top").click(function() {
$("html, body").animate({
scrollTop: 0
}, "slow");
window.icount = 0;
});
var icount = 0
$('.down-btn').on('click', function(e) {
e.preventDefault();
window.icount++;
var offset = $("div.next-section.yellow").eq(icount).offset().top;
$('html, body').stop().animate({
scrollTop: offset
}, 400);
});

How to hide single div at a time without flashing rather setting visibility hidden

i want to hide a single div at a time so that below flashing can be avoided(shown in image)
NOTE: i cannot use visibility:hidden or visibility:show or $sel.css('visibility','hidden'); or $sel.css('visibility','show');
My Expectation: when I do $content.hide(); in the DOM see html area in image provided by me where style="display:none"/style="display:block" is happening for every element, rather I want to hide that particular element at a time (so no multiple display/hide at a time, only one display/hide) similar to #snippet2, #snippet1 should work (but hidden element should not contain any width/height)
below is my code which should work with display:none or $el.hide()/$el.show():
#Snippet1
$(function() {
var pos = 1;
var ii = 0;
var centerbandTop = $('.center-band').offset().top;
var centerbandBottom = $('.center-band').outerHeight() + centerbandTop;
$('.contents').hide();
var intId = setInterval(function() {
ii++;
pos = -ii;
//console.log(pos);
//if (pos )
$('.contents').each(function() {
var $content = $(this);
var contentTop = $content.offset().top;
var contentBottom = $content.outerHeight() + contentTop;
$content.hide();
//console.log($content.position().top, centerbandTop, contentBottom);
if (centerbandBottom > contentTop && centerbandTop < contentBottom)
$content.show();
});
$('.container').css({
// '-webkit-transform' : 'translate(0,' + pos + ')',
transform: 'translateY(' + pos + 'px)'
});
}, 100);
});
.container{
width: 100%;
height: 100%;
background: #000000d6;
font-size: 19px;
color: #a19999;
position: relative;
}
.contents{
margin-bottom: 15px;
border-bottom: 1px solid #424242;
padding: 20px;
visibility: hidden;
}
.center-band{
width: 98%;
height: 78px;
z-index: 200;
background: #b4b1b147;
position: fixed;
top: 50%;
}
.wrapper{
position: relative;
}
.over{
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="contents"> (1) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="contents">(2) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, distinctio temporibus facere, laboriosam doloribus error quaerat ipsa, non nobis rerum mollitia quibusdam quas illo a qui consequuntur consectetur deleniti saepe.</div>
<div class="contents">(3) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Unde, sed, atque. Adipisci quasi debitis, soluta praesentium distinctio impedit veritatis officia molestias culpa fuga excepturi voluptates suscipit aliquam ea unde, non!</div>
<div class="contents">(4) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, incidunt, harum. Perferendis ipsum, molestias nihil sequi nam nulla, aliquid ipsa numquam cum! Perferendis ut voluptates hic excepturi dolores, ipsum impedit.</div>
<div class="contents">(5) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim itaque debitis voluptates, reiciendis dolorum, labore eius. Illum similique ex, iusto rerum ratione minima, corporis aspernatur aliquam, itaque numquam sint enim!</div>
<div class="contents">(6) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint numquam totam, a aliquam veritatis porro ullam! Nostrum sint ipsum odio aperiam deserunt aut placeat dignissimos est ad, quae vitae aliquid.</div>
<div class="contents">(7) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et quos atque enim, alias culpa quibusdam ratione, beatae non possimus, velit eaque. Optio qui saepe, earum harum beatae maxime obcaecati minima.</div>
<div class="contents">(8) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Hic id incidunt sapiente, magni, sequi ea molestiae iure maxime delectus doloribus error assumenda veritatis maiores saepe nihil neque autem similique obcaecati!</div>
<div class="contents">(9) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum velit hic iure nam nulla natus corrupti eveniet, suscipit voluptates nostrum. Cupiditate vero ipsam alias fuga, magnam voluptas deserunt corporis non!</div>
<div class="contents">(10) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae voluptatibus accusamus pariatur? Ipsum nobis ratione fuga, voluptates quam placeat officia odit eveniet aliquam, eaque quisquam tenetur! Exercitationem maxime vel quas!</div>
</div>
<div class="center-band"> </div>
</div>
Question: Above snippet(#snippet1) should work as same as below(#snippet2) one but without using visibility(#snippet2 Working without flashing)
#snippet2
$(function() {
var pos = 1;
var ii = 0;
var centerbandTop = $('.center-band').offset().top;
var centerbandBottom = $('.center-band').outerHeight() + centerbandTop;
var intId = setInterval(function() {
ii++;
pos = -ii;
//console.log(pos);
//if (pos )
$('.contents').each(function() {
var $content = $(this);
var contentTop = $content.offset().top;
var contentBottom = $content.outerHeight() + contentTop;
$content.css('visibility', 'hidden');
//console.log($content.position().top, centerbandTop, contentBottom);
if (centerbandBottom > contentTop && centerbandTop < contentBottom)
$content.css('visibility', 'visible');
});
$('.container').css({
// '-webkit-transform' : 'translate(0,' + pos + ')',
transform: 'translateY(' + pos + 'px)'
});
}, 100);
});
/* Styles go here */
.container{
width: 100%;
height: 100%;
background: #000000d6;
font-size: 19px;
color: #a19999;
position: relative;
}
.contents{
margin-bottom: 15px;
border-bottom: 1px solid #424242;
padding: 20px;
visibility: hidden;
}
.center-band{
width: 98%;
height: 78px;
z-index: 200;
background: #b4b1b147;
position: fixed;
top: 50%;
}
.wrapper{
position: relative;
}
.over{
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="contents"> (1) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="contents">(2) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, distinctio temporibus facere, laboriosam doloribus error quaerat ipsa, non nobis rerum mollitia quibusdam quas illo a qui consequuntur consectetur deleniti saepe.</div>
<div class="contents">(3) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Unde, sed, atque. Adipisci quasi debitis, soluta praesentium distinctio impedit veritatis officia molestias culpa fuga excepturi voluptates suscipit aliquam ea unde, non!</div>
<div class="contents">(4) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, incidunt, harum. Perferendis ipsum, molestias nihil sequi nam nulla, aliquid ipsa numquam cum! Perferendis ut voluptates hic excepturi dolores, ipsum impedit.</div>
<div class="contents">(5) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim itaque debitis voluptates, reiciendis dolorum, labore eius. Illum similique ex, iusto rerum ratione minima, corporis aspernatur aliquam, itaque numquam sint enim!</div>
<div class="contents">(6) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint numquam totam, a aliquam veritatis porro ullam! Nostrum sint ipsum odio aperiam deserunt aut placeat dignissimos est ad, quae vitae aliquid.</div>
<div class="contents">(7) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et quos atque enim, alias culpa quibusdam ratione, beatae non possimus, velit eaque. Optio qui saepe, earum harum beatae maxime obcaecati minima.</div>
<div class="contents">(8) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Hic id incidunt sapiente, magni, sequi ea molestiae iure maxime delectus doloribus error assumenda veritatis maiores saepe nihil neque autem similique obcaecati!</div>
<div class="contents">(9) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum velit hic iure nam nulla natus corrupti eveniet, suscipit voluptates nostrum. Cupiditate vero ipsam alias fuga, magnam voluptas deserunt corporis non!</div>
<div class="contents">(10) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae voluptatibus accusamus pariatur? Ipsum nobis ratione fuga, voluptates quam placeat officia odit eveniet aliquam, eaque quisquam tenetur! Exercitationem maxime vel quas!</div>
</div>
<div class="center-band"> </div>
</div>
Please help me thanks in advance!!!
It is hard to understand your question, but from the code snippets you provided it looks like you need to fundamentally rethink your approach.
Your code moves the "container" div up and then computes the positions of the contained elements, but the problem is that when you hide or show an element all the other elements move in response. So when "contents 1" gets above the center band and you hide it, it stops taking up space and "contents 2" moves to where "contents 1" was. However, since "contents 1" was above the center band, now "contents 2" is above the center band and you are going to hide that, too. And so in your code, as soon as "contents 1" gets above the center band, all the contents will be hidden.
There are many ways to handle this, and the best way for your situation will probably depend on details of what you are truly trying to accomplish and which are not clear from your question. Using CSS overflow: hidden is probably the most efficient and you do not really explain what is wrong with that solution.
Another option is to adjust the position of the container to compensate for hiding the element. You also have to have some way to figure out when to show items that enter the box, which you cannot do from their position, because they are hidden. This snippet is not ideal, and there are some glitches because of margins, but it shows the concept.
$(function() {
var pos = 0;
var showNext = false;
var centerbandTop = $('.center-band').offset().top;
var centerbandBottom = $('.center-band').outerHeight() + centerbandTop;
var scroll = function() {
pos--; // move the list up one pixel
$('.contents').each(function() {
var $content = $(this);
// If the previous "contents" moved up enough
// to make room for this hidden element, show it.
if (showNext) {
$content.show();
showNext = false;
} else if ($content.is(':hidden')) // nothing to do
return;
// We have to wait until after we have shown
// the element to compute its position.
var contentTop = $content.offset().top;
var contentBottom = $content.outerHeight() + contentTop;
if (contentBottom < centerbandTop) {
// If the element has exited the top of the
// band, hide it, and move the container
// down to compensate for removing this
// element.
pos = pos + $content.outerHeight(true);
$content.hide();
} else if (contentTop > centerbandBottom) {
// If the element is below the band,
// hide it. Really this only needs to
// be done the first time through.
$content.hide();
}
// If there is room in the center band
// below this element, show the next one
showNext = contentBottom < centerbandBottom;
$('.container').css({
transform: 'translateY(' + pos + 'px)'
});
});
}
// We start with the contents "visibility: hidden"
// and all the elements displayed so we do not
// see them but still can compute their positions.
// One pass through scroll() then hides everything
// that needs to be hidden.
scroll();
// Now we can make everthing visible
$('.contents').css('visibility', 'visible');
// And now we set up the scrolling timer
var intId = setInterval(scroll, 100);
});
/* Styles go here */
.container {
width: 100%;
height: 100%;
background: #000000d6;
font-size: 19px;
color: #a19999;
position: relative;
}
.contents {
margin-bottom: 15px;
border-bottom: 1px solid #424242;
padding: 20px;
visibility: hidden;
}
.center-band {
width: 98%;
height: 78px;
z-index: 200;
background: #b4b1b147;
position: fixed;
top: 50%;
}
.wrapper {
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="contents"> (1) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="contents">(2) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, distinctio temporibus facere, laboriosam doloribus error quaerat ipsa, non nobis rerum mollitia quibusdam quas illo a qui consequuntur consectetur deleniti saepe.</div>
<div class="contents">(3) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Unde, sed, atque. Adipisci quasi debitis, soluta praesentium distinctio impedit veritatis officia molestias culpa fuga excepturi voluptates suscipit aliquam ea unde, non!</div>
<div class="contents">(4) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, incidunt, harum. Perferendis ipsum, molestias nihil sequi nam nulla, aliquid ipsa numquam cum! Perferendis ut voluptates hic excepturi dolores, ipsum impedit.</div>
<div class="contents">(5) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim itaque debitis voluptates, reiciendis dolorum, labore eius. Illum similique ex, iusto rerum ratione minima, corporis aspernatur aliquam, itaque numquam sint enim!</div>
<div class="contents">(6) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint numquam totam, a aliquam veritatis porro ullam! Nostrum sint ipsum odio aperiam deserunt aut placeat dignissimos est ad, quae vitae aliquid.</div>
<div class="contents">(7) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et quos atque enim, alias culpa quibusdam ratione, beatae non possimus, velit eaque. Optio qui saepe, earum harum beatae maxime obcaecati minima.</div>
<div class="contents">(8) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Hic id incidunt sapiente, magni, sequi ea molestiae iure maxime delectus doloribus error assumenda veritatis maiores saepe nihil neque autem similique obcaecati!</div>
<div class="contents">(9) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum velit hic iure nam nulla natus corrupti eveniet, suscipit voluptates nostrum. Cupiditate vero ipsam alias fuga, magnam voluptas deserunt corporis non!</div>
<div class="contents">(10) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae voluptatibus accusamus pariatur? Ipsum nobis ratione fuga, voluptates quam placeat officia odit eveniet aliquam, eaque quisquam tenetur! Exercitationem maxime vel quas!</div>
</div>
<div class="center-band"> </div>
</div>
Initially calculate the vertical beginning/ending values of all divs and store this data independently. Make all divs visible (display !== 'none')in the DOM very briefly, while using opacity to hide them, in order to calculate their heights (no way to calculate div height without attaching it to the DOM).
Also need to make all scrollable items position: absolute so that their removal doesn't reflow the items beneath them. This means javascript also needs to calculate top positions for items.
Then, whenever things change (whenever new items potentially need to be shown/hidden) check all independently stored position data against the position of the "hot zone" (the zone with which contact causes visibility).
window.onload = () => {
let positions = []; // Independently store positional data for text items
// Keep references to some useful DOM elements
let hotZone = document.getElementsByClassName('hot-zone')[0];
let scroller = document.getElementsByClassName('scroller')[0];
let scrollerHeight = scroller.getElementsByClassName('height')[0];
let items = document.getElementsByClassName('item');
let totalHeight = 0; // We'll track total height of items as we go
for (let i = 0; i < items.length; i++) {
let { height } = items[i].getBoundingClientRect();
items[i].style.top = `${Math.round(totalHeight)}px`;
items[i].style.display = 'none';
positions.push([ totalHeight, height ]);
totalHeight += height;
}
// Make sure the scroller doesn't shrink when we remove its children
scrollerHeight.style.height = `${Math.round(totalHeight)}px`;
let reevaluate = () => {
let hotRect = hotZone.getBoundingClientRect();
let scrollRect = scroller.getBoundingClientRect();
for (let i = 0; i < items.length; i++) {
let [ itemTop, itemHeight ] = positions[i];
itemTop += scrollRect.top; // Make relative to scroller
itemTop -= scroller.scrollTop; // Make relative to scroll amt
let tooHigh = itemTop + itemHeight < hotRect.top;
let tooLow = itemTop > hotRect.bottom;
let disp = (tooHigh || tooLow) ? 'none' : 'block';
if (disp !== items[i].style.display) items[i].style.display = disp;
}
};
// Immediately call `reevaluate` to initially show items
reevaluate();
// Now everything is nice so make the scroller completely opaque
document.getElementsByClassName('scroller')[0].style.opacity = '1';
// Setup listeners to call `reevaluate` when there's a possibility
// new items need to show. E.g., the "hot zone" has moved, the items
// have moved, scrolls have happened, etc.
scroller.addEventListener('scroll', reevaluate);
};
.contain {
position: fixed;
left: 0; top: 0;
width: 100%; height: 100%;
background-color: #000000;
}
.scroller {
position: relative;
left: 0; top: 0;
width: 100%; height: 100%;
overflow-x: hidden;
overflow-y: scroll;
color: #ffffff;
opacity: 0; /* Initially invisible (to avoid 1-frame flicker) */
}
.scroller > .height {
position: relative;
width: 0; height: 0; /* Invisible; lends the scroller its height */
}
.scroller > .item {
position: absolute;
left: 0; top: 0;
width: 100%;
outline: 1px solid rgba(255, 0, 0, 0.8);
}
.hot-zone {
position: absolute;
left: 0; top: 30%;
width: 100%; height: 20%;
background-color: rgba(255, 255, 255, 0.6);
box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.8);
z-index: 2;
pointer-events: none;
}
<div class="contain">
<div class="hot-zone"></div>
<div class="scroller">
<div class="height"></div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Not too much here :)</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">THIS<br/>ONE<br/>IS<br/>REALLY<br/>QUITE<br/>LONG<br/>INDEED<br/>GOOD<br/>SIR</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
</div>
</div>
So you said in your comment that
but my requirement is whichever content touches that gray band should
be shown otherwise it has to be hidden holding no width and height
From this I understand that you need a vertical text scroller. Why don't you use the gray band div as a container, with overflow hidden, and then scroll the content through it?
$(function() {
var pos = 1;
var ii = 0;
var centerbandTop = $('.center-band').offset().top;
var centerbandBottom = $('.center-band').outerHeight() + centerbandTop;
//$('.contents').hide();
var intId = setInterval(function() {
ii++;
pos = -ii;
//console.log(pos);
//if (pos )
$('.contents').each(function() {
var $content = $(this);
var contentTop = $content.offset().top;
var contentBottom = $content.outerHeight() + contentTop;
//$content.hide();
//console.log($content.position().top, centerbandTop, contentBottom);
//if (centerbandBottom > contentTop && centerbandTop < contentBottom)
//$content.show();
});
$('.container').css({
// '-webkit-transform' : 'translate(0,' + pos + ')',
transform: 'translateY(' + pos + 'px)'
});
}, 100);
});
.container{
width: 100%;
/*height: 100%;*/
background: #000000d6;
font-size: 19px;
color: #a19999;
position: relative;
}
.contents{
margin-bottom: 15px;
border-bottom: 1px solid #424242;
padding: 20px;
/*visibility: hidden;*/
}
.center-band{
width: 98%;
height: 78px;
z-index: 200;
background: #b4b1b147;
position: relative;
/*top: 50%;*/
overflow: hidden;
}
.wrapper{
position: relative;
}
.over{
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div>
some static text above
</div>
<div class="center-band">
<div class="container">
<div class="contents"> (1) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus fugit eius perferendis veritatis accusantium corporis nulla alias sed possimus quibusdam reiciendis nisi maiores inventore error, incidunt eveniet ut asperiores officiis.</div>
<div class="contents">(2) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, distinctio temporibus facere, laboriosam doloribus error quaerat ipsa, non nobis rerum mollitia quibusdam quas illo a qui consequuntur consectetur deleniti saepe.</div>
<div class="contents">(3) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Unde, sed, atque. Adipisci quasi debitis, soluta praesentium distinctio impedit veritatis officia molestias culpa fuga excepturi voluptates suscipit aliquam ea unde, non!</div>
<div class="contents">(4) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, incidunt, harum. Perferendis ipsum, molestias nihil sequi nam nulla, aliquid ipsa numquam cum! Perferendis ut voluptates hic excepturi dolores, ipsum impedit.</div>
<div class="contents">(5) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim itaque debitis voluptates, reiciendis dolorum, labore eius. Illum similique ex, iusto rerum ratione minima, corporis aspernatur aliquam, itaque numquam sint enim!</div>
<div class="contents">(6) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint numquam totam, a aliquam veritatis porro ullam! Nostrum sint ipsum odio aperiam deserunt aut placeat dignissimos est ad, quae vitae aliquid.</div>
<div class="contents">(7) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et quos atque enim, alias culpa quibusdam ratione, beatae non possimus, velit eaque. Optio qui saepe, earum harum beatae maxime obcaecati minima.</div>
<div class="contents">(8) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Hic id incidunt sapiente, magni, sequi ea molestiae iure maxime delectus doloribus error assumenda veritatis maiores saepe nihil neque autem similique obcaecati!</div>
<div class="contents">(9) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum velit hic iure nam nulla natus corrupti eveniet, suscipit voluptates nostrum. Cupiditate vero ipsam alias fuga, magnam voluptas deserunt corporis non!</div>
<div class="contents">(10) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae voluptatibus accusamus pariatur? Ipsum nobis ratione fuga, voluptates quam placeat officia odit eveniet aliquam, eaque quisquam tenetur! Exercitationem maxime vel quas!</div>
</div>
</div>
<div>
some static text below
</div>
</div>

CSS Change Background Color at Certain Point

I would like the background of the entire site to change from white to black when a certain element comes into view. So when you scroll by the element the background transitions to black. When you scroll back up I want the background color of the page to change back to white. Thank you!
HTML:
<div id="#block-yui_3_17_2_2_1495044195108_28541" class="colorChange">
<script>
$(window).scroll(function () {
$('#block-yui_3_17_2_2_1495044195108_28541').each(function () {
var topOfWindow = $(window).scrollTop(),
bottomOfWindow = topOfWindow + $(window).height();
var imagePos = $(this).offset().top;
if(imagePos <= bottomOfWindow-100 && imagePos >= topOfWindow-250){
$(this).addClass('colorChange');
}else{
$(this).removeClass('colorChange');
}
});
});
</script>
CSS:
.colorChange{
#siteWrapper {
-webkit-animation-name: colorChange;
-webkit-animation-duration: 1s;
-webkit-animation-timing-function: ease-in;
animation-name: colorChange;
animation-duration: 1s;
animation-timing-function: ease-in;
}}
#-webkit-keyframes colorChange {
0% {
background-color:black;
}
100.0% {
background-color:black;
}
}
#keyframes colorChange {
0% {
background-color:black;
}
100.0% {
background-color:black;
}
}
Using the scroll event you can calculate the offset of the h1 (or whatever element) which gets the current coordinates of the element. the wScroll variable gets the current vertical position of the scroll bar in this case the top of the window. On the condition you check if the scrollbar is greater or equal to the element you which to target and subtract that from the window height (if you wish to change the background once the element is on the screen change the 1.2 to 1) add a transition to the body for the animation. Check the demo scroll down.
Sorry if its not well explained, excuse my writing.
$(window).scroll(function(){
var wScroll = $(this).scrollTop();
if(wScroll >= $('h1').offset().top - ($(window).height() / 1.2 ) ){
$("body").css("background-color", "black");
}else{
$("body").css("background-color", "white");
}
});
body{
transition: background-color 0.3s ease-in-out;
}
p{height: 1000px;}
h1{
height: 400px;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hei">
<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. </p>
<h1>Change to Black</h1>
</div>
Your $(window).scroll is correct but i think your code lacks the proper setup to do what you want. Here is a working sample i made from your code to change the color of the background when the block div comes into view when scrolling.
https://codepen.io/Nasir_T/pen/jmvwEP
Hope this helps.
If you only want something to happen when the element is in the viewport, you can find the top/bottom positions of the element and compare it to the scrolled distance and bottom of the window.
$(window).on('resize scroll',function() {
var $div = $('div'),
$body = $('body'),
st = $(this).scrollTop(),
wh = $(this).height(),
wb = st + wh,
dh = $div.height(),
dt = $div.offset().top,
db = dh + dt;
if (dt < wb && db > st) {
$body.addClass('color');
} else {
$body.removeClass('color');
}
})
section {
height: 150vh;
}
div {
background: black;
height: 200px;
}
.color {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section></section>
<div></div>
<section></section>
I assume your real issue are the first to lines in your CSS which is not valid. Have a look at the reference. If you want to select all .colorChange inside of #pageWrapper use:
#siteWrapper .colorChange {}
Also remove the "#" in your HTML like so:
<div id="block-yui_3_17_2_2_1495044195108_28541" class="colorChange">
I also would recommend you two throttle your events, so that you do not listen to every scroll event, which could dramatically slow down your system, but every 50 seconds or so. Have a look at ScrollSpy or some jquery throtte plugin.

Jquery each loop, find height of right side and add it to left side.

This might be an easy question for some people, but I can’t seem to get it right. I have some floated div’s. The ‘right side’ is taller than the ‘left side’. What I would like to do is, take the height of the ‘right side’ and add it to the ‘left side’.
I’m trying an each loop, but all i end up with is the last height of the ‘right side’. Anyone have any ideas?
<style>
.left, .right{
float: left;
width: 50%;
box-sizing: border-box;
padding: 1em;
border: 1px solid red;
}
</style>
<div class="container">
<div class="left"/><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate aspernatur, dolore, totam alias beatae, modi distinctio voluptatum omnis blanditiis veniam quidem a itaque enim eos dolorum animi nobis nihil nemo!</p></div>
<div class="right"/><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate aspernatur, dolore, totam alias beatae, modi distinctio voluptatum omnis blanditiis veniam quidem a itaque enim eos dolorum animi nobis nihil nemo!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium ipsum vero illo, earum nemo molestiae ratione, sunt tempore iusto ad dolorem minima atque debitis dolor recusandae dolorum id optio dolore. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda quaerat numquam porro placeat aliquam sint fugit reprehenderit suscipit similique commodi minus magnam quod quis, cum nesciunt autem error, eum quasi.</p>
</div>
<div class="left"/><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate aspernatur, dolore, totam alias beatae, modi distinctio voluptatum omnis blanditiis veniam quidem a itaque enim eos dolorum animi nobis nihil nemo!</p></div>
<div class="right"/><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate aspernatur, dolore, totam alias beatae, modi distinctio voluptatum omnis blanditiis veniam quidem a itaque enim eos dolorum animi nobis nihil nemo!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium ipsum vero illo, earum nemo molestiae ratione, sunt tempore iusto ad dolorem minima atque debitis dolor recusandae dolorum id optio dolore.</p>
</div>
</div>
<script>
$(document).ready(function() {
var $left_side = $('.left');
var $right_side = $('.right');
var the_height = [];
$('.container').each(function(index, val) {
var elHeight = $(val).height();
the_height.push(elHeight);
});
});
Thats because you are interating over the amount of $(".container") instead of the <div class="right">
$(document).ready(function() {
var $left_side = $('.left');
var $right_side = $('.right');
var the_height = [];
$('.right').each(function(index, val) {
var elHeight = $(val).height();
the_height.push(elHeight);
});
});
If you are trying to make the left <div class="left"> the same height as the right <div class="right"> you can do:
$(document).ready(function() {
$('.right').each(function(index, val) {
$(this).prev('.left').height($(this).height());
});
});
$(document).ready(function(){
var $left_side = $('.left');
var $right_side = $('.right');
var the_height = [];
var divs=$(".container").children();
$(divs).each(function(index,val){
the_height.push($(this).height())
})
})
this shuld also work
$('.container') is just one div. I think you want to loop through the children the .container. This is one of the ways you can do:
$(document).ready(function() {
var $left_side = $('.left');
var $right_side = $('.right');
var the_height = [];
$('.container').children().each(function(index, val) {
var elHeight = $(val).height();
the_height.push(elHeight);
});
});
Judging from what you said you want to accomplish, I'd say the code is not going to work properly. Here's a code that adds the right height to the left one:
$(document).ready(function() {
$('.container').each(function() {
var right_height = $(this).children("div.right").height();
var left_height = $(this).children("div.left").height();
$(this).children("div.left").height(right_height + left_height)
});
});
Also, all your divs are wrong! You're not supposed to close them in the opening tag:
<div class="left"/>
You have to remove the slash:
<div class="left">

Categories

Resources