How to avoid writing to DOM while scrolling? - javascript

I need to change container heading according to what child is scrolled into view at the moment. The container has fixed height and overflow:hidden
The HTML is something like this:
<h2 class="heading">Item 1</h2>
<div class="dealers-scrollable">
<div class="dealer-group">
<h3 class="group-head">Item 1</h3>
...
</div>
<div class="dealer-group">
<h3 class="group-head">Item 2</h3>
...
</div>
<div class="dealer-group">
<h3 class="group-head">Item 3</h3>
...
</div>
</div>
Here is my code:
$(".dealers-scrollable").mCustomScrollbar({
callbacks: {
whileScrolling: function(){
changeHeading(this);
}
}
});
var changeHeading = (function () {
return function(el) {
var blockPosition,
elementPosition,
currentHeading;
$(".dealer-group").each(function () {
blockPosition = Math.abs(el.mcs.top);
elementPosition = $(this).position().top;
if (blockPosition > elementPosition) {
currentHeading = $(this).find(".group-head").text();
$(".heading").text(currentHeading);
}
});
}
})();
This code does the job. But the problem is it writes into DOM on every scroll even if the current block is still in view. This is bad and I want to avoid it. I wrapped the function in closure and wanted to use a flag, but with no luck.
Please advise what can be done to avoid constant wring to DOM on scroll?
https://jsfiddle.net/gwht91cj/

Check out this JSFiddle
What I did was create a variable to store all the blocks currently in view (or scrolled past), and used a .each() to add each index to the array:
var elemIndexInView = []
// Add index of each element that has been scrolled past
$(".dealer-group").each(function(index) {
blockPosition = Math.abs(el.mcs.top);
elementPosition = $(this).position().top;
if (blockPosition > elementPosition) {
elemIndexInView.push(index)
}
});
Then, inside your original .each() loop, I changed the if statement to this:
if (blockPosition > elementPosition) {
currentHeading = $(this).children(".group-head").text();
if (
$('.heading').text() != currentHeading &&
index == elemIndexInView[elemIndexInView.length - 1]
) {
$(".heading").text(currentHeading);
// alert('Written to DOM')
// alert(currentHeading)
}
}
$(".dealers-scrollable").mCustomScrollbar({
callbacks: {
whileScrolling: function() {
changeHeading(this);
}
}
});
var changeHeading = (function() {
return function(el) {
var blockPosition,
elementPosition,
currentHeading;
var elemIndexInView = []
// Add index of each element that has been scrolled past
$(".dealer-group").each(function(index) {
blockPosition = Math.abs(el.mcs.top);
elementPosition = $(this).position().top;
if (blockPosition > elementPosition) {
elemIndexInView.push(index)
}
});
$(".dealer-group").each(function(index, element) {
blockPosition = Math.abs(el.mcs.top);
elementPosition = $(this).position().top;
if (blockPosition > elementPosition) {
currentHeading = $(this).children(".group-head").text();
if (
$('.heading').text() != currentHeading &&
index == elemIndexInView[elemIndexInView.length - 1]
) {
$(".heading").text(currentHeading);
// alert('Written to DOM')
// alert(currentHeading)
}
}
});
}
})();
.dealers-scrollable {
width: 600px;
height: 300px;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.mcustomscrollbar/3.0.6/jquery.mCustomScrollbar.concat.min.js"></script>
<link href="https://cdn.jsdelivr.net/jquery.mcustomscrollbar/3.0.6/jquery.mCustomScrollbar.min.css" rel="stylesheet"/>
<h2 class="heading">Item 1</h2>
<div class="dealers-scrollable">
<div class="dealer-group">
<h3 class="group-head">Item 1</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
</div>
<div class="dealer-group">
<h3 class="group-head">Item 2</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
</div>
<div class="dealer-group">
<h3 class="group-head">Item 3</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat consequuntur nemo accusamus expedita minima, tenetur, esse nisi vel voluptas totam reiciendis harum dolorum similique voluptatem commodi deserunt, earum veritatis animi.</p>
</div>
</div>

Related

Javascript Auto-scroll Appears Jittery on Safari IOS

The Objective
I am trying to make an auto-scrolling feature for an online ebook reader website. The user must be able to press a button and have the page scroll automatically.
The problem
Every solution I have found so far uses either setTimeout or setInterval to scroll the page with window.scrollBy(0, 1), and this works great on chrome, however when I test this on Safari IOS, the page does not scroll smoothly at all. It appears very jittery, to the point that the text is no longer legible.
Here is a video demonstrating the problem. (Please watch in 1080p60, since the jitter is more apparent at 60fps)
The code
Here is a simple HTML document to demonstrate my current method of auto scrolling.
let scrollTimeout;
function pageScroll() {
scrollTimeout = setTimeout(() => {
window.scrollBy(0, 1);
pageScroll();
}, 10);
}
function startScroll() {
pageScroll();
}
function stopScroll() {
clearTimeout(scrollTimeout);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Test Auto-scroll</title>
</head>
<body>
<main style="max-width: 500px; margin: 0 auto; font-size: 32px">
<div style="position: sticky; top: 0">
<button onclick="startScroll()">Start</button>
<button onclick="stopScroll()">Stop</button>
</div>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum
ducimus, totam debitis sint modi inventore explicabo iusto
assumenda vitae vero porro aperiam aut reiciendis nam culpa quia
in, dolor quae.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Impedit sunt vitae saepe recusandae voluptatibus nihil enim,
sequi rerum quibusdam nisi provident! Autem aliquid
reprehenderit doloremque inventore quasi dolore fugit tempora.
</p>
<p>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Iure
molestias consectetur molestiae labore totam ex et eum nulla
officia, minima excepturi voluptates, consequatur amet modi!
Molestiae autem illum ullam accusantium.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Quisquam ab ex tenetur a possimus? Cum, nostrum dolor? Veniam
tenetur cupiditate, maxime fuga sequi earum excepturi
repudiandae, aliquam, laborum blanditiis iusto.
</p>
<p>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsam,
laborum mollitia suscipit dolores omnis, cum perferendis rerum
accusantium doloremque quasi pariatur, deserunt delectus et
porro nesciunt cumque vel quisquam velit!
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Quisquam ab ex tenetur a possimus? Cum, nostrum dolor? Veniam
tenetur cupiditate, maxime fuga sequi earum excepturi
repudiandae, aliquam, laborum blanditiis iusto.
</p>
<p>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsam,
laborum mollitia suscipit dolores omnis, cum perferendis rerum
accusantium doloremque quasi pariatur, deserunt delectus et
porro nesciunt cumque vel quisquam velit!
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Quisquam ab ex tenetur a possimus? Cum, nostrum dolor? Veniam
tenetur cupiditate, maxime fuga sequi earum excepturi
repudiandae, aliquam, laborum blanditiis iusto.
</p>
<p>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsam,
laborum mollitia suscipit dolores omnis, cum perferendis rerum
accusantium doloremque quasi pariatur, deserunt delectus et
porro nesciunt cumque vel quisquam velit!
</p>
</main>
</body>
</html>
Apple throttles their devices to give supposedly battery performance. But there are other reasons like Background App Refresh, Low Battery More, and many more. The easily visible reason is Low Power Mode on you will not get the same performance as Low Power More off.
With your snippet, you can clearly judge the performance difference between Low Power Mode on and Low Power Mode off.
Also, performance can be affected by the display refresh rate. You can manage it with requestAnimationFrame, where you can somewhat control fps.
The below example could help you with requestAnimationFrame.
let scrollAnimationFrame;
let prevtimeStamp = 0;
let deltaTime = 0;
let functionTiming = 10;
let counter = 0;
let reachedBottom = false;
function animateScroll(timestamp) {
const deltaTime = timestamp - prevtimeStamp;
prevtimeStamp = timestamp;
const scrollY = window.scrollY;
if(counter > functionTiming){
window.scrollBy(0, 1);
counter = 0;
if(scrollY === window.scrollY)
reachedBottom = true;
}else{
counter += deltaTime;
}
if(reachedBottom)
cancelAnimationFrame(scrollAnimationFrame);
else
scrollAnimationFrame = requestAnimationFrame(animateScroll);
}
function startScroll() {
if(!scrollAnimationFrame)
animateScroll(0);
}
function stopScroll() {
if(scrollAnimationFrame)
cancelAnimationFrame(scrollAnimationFrame);
scrollAnimationFrame = 0;
}
document.getElementById('functionTimingControl').addEventListener('change', function(e){
functionTiming = e.target.value;
});
<main style="max-width: 500px; margin: 0 auto; font-size: 32px">
<div style="position: sticky; top: 0">
<button onclick="startScroll()">Start</button>
<button onclick="stopScroll()">Stop</button>
<input type='number' min='1' max='1000' value='10' id='functionTimingControl' />
</div>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum ducimus, totam debitis sint modi inventore explicabo iusto assumenda vitae vero porro aperiam aut reiciendis nam culpa quia in, dolor quae.
</p>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum ducimus, totam debitis sint modi inventore explicabo iusto assumenda vitae vero porro aperiam aut reiciendis nam culpa quia in, dolor quae.
</p>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum ducimus, totam debitis sint modi inventore explicabo iusto assumenda vitae vero porro aperiam aut reiciendis nam culpa quia in, dolor quae.
</p>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum ducimus, totam debitis sint modi inventore explicabo iusto assumenda vitae vero porro aperiam aut reiciendis nam culpa quia in, dolor quae.
</p>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum ducimus, totam debitis sint modi inventore explicabo iusto assumenda vitae vero porro aperiam aut reiciendis nam culpa quia in, dolor quae.
</p>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum ducimus, totam debitis sint modi inventore explicabo iusto assumenda vitae vero porro aperiam aut reiciendis nam culpa quia in, dolor quae.
</p>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum ducimus, totam debitis sint modi inventore explicabo iusto assumenda vitae vero porro aperiam aut reiciendis nam culpa quia in, dolor quae.
</p>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum ducimus, totam debitis sint modi inventore explicabo iusto assumenda vitae vero porro aperiam aut reiciendis nam culpa quia in, dolor quae.
</p>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum ducimus, totam debitis sint modi inventore explicabo iusto assumenda vitae vero porro aperiam aut reiciendis nam culpa quia in, dolor quae.
</p>
</main>

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>

How to hide other div apart from touched div to the band

I want to hide other divs apart from touched div to the band
the band is this element <div class="center-band"></div>
whenever the scrolling element touches the element <div class="center-band"></div> then it has to be shown, and other divs have to be hidden
Question: only touched div to the band has to be shown, and others has to be hidden, that means only one content has to be shown at a time.
jsbin: https://jsbin.com/zudideheza/edit?html,css,js,console,output
$(function()
{
var pos = 1;
var ii = 0;
var intId = setInterval(function()
{
ii++;
pos = - ii;
//console.log(pos);
$('.container').css({
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;
}
.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" style="transform:translateY(0px);">
<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>
Note: I don't want to change scrolling content approach (question is not about positioning)
Please help me thanks in advance!!!!
Try this out:
$(function()
{
var pos = 1;
var ii = 0;
var intId = setInterval(function()
{
ii++;
pos = - ii;
//console.log(pos);
$('.inner-content').css({
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;*/
}
.show{
/*visibility: visible;*/
}
.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=" center-band" style="overflow-y:hidden;">
<div class="inner-content" style=" transform:translateY(0px);">
<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>
</div>
It depends on whether you want to include the margins or not, but you can use the following to detect the positions and then apply the class over to the .content divs that are currently hovered over:
$(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;
$('.contents').each(function() {
var $content = $(this);
var contentTop = $content.offset().top;
var contentBottom = $content.outerHeight() + contentTop;
$content.removeClass('over');
if (centerbandBottom > contentTop && centerbandTop < contentBottom)
$content.addClass('over');
});
$('.container').css({
// '-webkit-transform' : 'translate(0,' + pos + ')',
transform: 'translateY(' + pos + 'px)'
});
}, 100);
});
Demo: http://plnkr.co/edit/YwaPy3qz07goW5ZfwARl
This is not exactly the direct answer to your questions, but another approach to solve this. May be this will help you somehow.
var domRect = document.getElementById('center-band').getBoundingClientRect();
var centerBandTop = domRect.top+20;
var centerBandBottom = domRect.top + 58;
$(function(){
var pos = 1;
var ii = 0;
var intId = setInterval(function(){
ii++;
pos =- ii;
$('.container').css({
transform : 'translateY('+pos+'px)'
});
$('.contents').each(function(idx,ele){
var domContent = document.getElementsByClassName('contents')[idx].getBoundingClientRect();
// console.log(idx +'---'+ domContent.top)
if(domContent.top < centerBandBottom && domContent.bottom > centerBandTop ){
//$(ele).text('');
}
else{
//$(ele).css('color','#fff');
}
})
},100);
});
.container{
z-index:999;
width: 100%;
height: 100%;
/*background: #222;*/
font-size: 19px;
color: #222;
position: relative;
}
.contents{
margin-bottom: 15px;
/* border-bottom: 1px solid #424242;*/
padding: 20px;
color:#fff;
}
#center-band{
width: 98%;
height: 78px;
background: #222;
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" style="transform:translateY(0px);">
<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.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 id="center-band"> </div>
</div>

div opacity on scroll top

I am trying to fade out the each blocks while scrolling top. When the particular div reached browser top it should slowly fade away.
I have tried but the problem here is that it is fading out all the divs since all divs have the same class name. I do not want to change the html structure for some reasons.
Is there any way to apply this effect on each divs?
var header = $('.content');
var range = 200;
$(window).on('scroll', function () {
var scrollTop = $(this).scrollTop();
var offset = header.offset().top;
var height = header.outerHeight();
offset = offset + height / 2;
var calc = 1 - (scrollTop - offset + range) / range;
header.css({ 'opacity': calc });
if ( calc > '1' ) {
header.css({ 'opacity': 1 });
} else if ( calc < '0' ) {
header.css({ 'opacity': 0 });
}
});
DEMO
I updated your fiddle. Basically, I did the calculation for each div separately by wrapping your code with .each
Check out this different version of answer fiddle.
header.each(function(){
if($(this).position().top - scrollTop <= 0){
$(this).css({ 'opacity': 0 });
}else{
$(this).css({ 'opacity': 1 });
}
You have to calculate the opacity for each element of the class.
Also you have to add a parent element with overflow-y:auto;
var parent = $("#parent");
var childs = $(".content");
var offset_top = 0;
var range = 200;
parent.on('scroll', function () {
var scrollTop = $(this).scrollTop();
if(scrollTop<20){
childs.css("opacity",1);
}
else{
childs.each(function(){
var top = $(this).offset().top - offset_top;
var height = $(this).height();
var offset = height/4;
var opacity = (top+ height - offset) / range;
if(opacity>1) opacity = 1;
else if(opacity<0) opacity = 0;
$(this).css("opacity",opacity);
});
}
});
div {color:#fff; padding:5%}
.content:nth-child(1){background:blue}
.content:nth-child(2){background:grey}
.content:nth-child(3){background:black}
.content:nth-child(4){background:red}
body,html{
height:100%;
}
#parent{
height:50%;
overflow-y:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum animi quos magnam earum nam itaque, sint rerum quibusdam voluptatibus, ipsam accusamus libero accusantium eveniet voluptatem quas, est tenetur eius aliquid.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum animi quos magnam earum nam itaque, sint rerum quibusdam voluptatibus, ipsam accusamus libero accusantium eveniet voluptatem quas, est tenetur eius aliquid.
</div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit perspiciatis temporibus accusantium aspernatur sint, commodi, dolor. Itaque, repudiandae ipsum consequatur, libero quisquam enim. Omnis architecto optio, eaque sapiente quia veritatis? Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum animi quos magnam earum nam itaque, sint rerum quibusdam voluptatibus, ipsam accusamus libero accusantium eveniet voluptatem quas, est tenetur eius aliquid.
</div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit perspiciatis temporibus accusantium aspernatur sint, commodi, dolor. Itaque, repudiandae ipsum consequatur, libero quisquam enim. Omnis architecto optio, eaque sapiente quia veritatis? Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum animi quos magnam earum nam itaque, sint rerum quibusdam voluptatibus, ipsam accusamus libero accusantium eveniet voluptatem quas, est tenetur eius aliquid.
</div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit perspiciatis temporibus accusantium aspernatur sint, commodi, dolor. Itaque, repudiandae ipsum consequatur, libero quisquam enim. Omnis architecto optio, eaque sapiente quia veritatis? Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum animi quos magnam earum nam itaque, sint rerum quibusdam voluptatibus, ipsam accusamus libero accusantium eveniet voluptatem quas, est tenetur eius aliquid.
</div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit perspiciatis temporibus accusantium aspernatur sint, commodi, dolor. Itaque, repudiandae ipsum consequatur, libero quisquam enim. Omnis architecto optio, eaque sapiente quia veritatis? Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum animi quos magnam earum nam itaque, sint rerum quibusdam voluptatibus, ipsam accusamus libero accusantium eveniet voluptatem quas, est tenetur eius aliquid.
</div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit perspiciatis temporibus accusantium aspernatur sint, commodi, dolor. Itaque, repudiandae ipsum consequatur, libero quisquam enim. Omnis architecto optio, eaque sapiente quia veritatis? Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum animi quos magnam earum nam itaque, sint rerum quibusdam voluptatibus, ipsam accusamus libero accusantium eveniet voluptatem quas, est tenetur eius aliquid.
</div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit perspiciatis temporibus accusantium aspernatur sint, commodi, dolor. Itaque, repudiandae ipsum consequatur, libero quisquam enim. Omnis architecto optio, eaque sapiente quia veritatis? Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum animi quos magnam earum nam itaque, sint rerum quibusdam voluptatibus, ipsam accusamus libero accusantium eveniet voluptatem quas, est tenetur eius aliquid.
</div>
</div>

Floating background when collapse a div

I have the following code to make divs collapse but I've realised that when I have a background colour there is a gap between the bar and content. Can anyone figure out how I can remove that gap?
https://jsfiddle.net/upxL42rw/1/
(function($) {
$.fn.collapse = function(method, options) {
var settings = $.extend({
collapse: "collapse",
signTag: "<span></span>",
titles: "h3",
titlesChild: "span",
container: "div",
classOpen: "opened",
open: "+",
close: "−",
rlOpen: "rl-open",
rlClose: "rl-close"
}, options);
var $element = $(this).children(settings.titles);
var $symbols = $(settings.signTag);
var $signOpen = $symbols.html(settings.open);
var $signClose = $symbols.html(settings.close);
var $insertElement = $symbols.appendTo($element);
$element.parent().addClass(settings.collapse);
if ($element.next().hasClass(settings.classOpen)) {
$element.children().html(settings.close).addClass(settings.rlClose);
} else {
$element.children().html(settings.open).addClass(settings.rlOpen);
}
var methods = {
single: function() {
return this.each(function() {
$(this).find(settings.container).eq(settings.childNum).addClass(settings.classOpen).slideDown()
.prev().children().html(settings.close).removeClass(settings.rlOpen).addClass(settings.rlClose);
$element.on('click', function() {
$(this).next().slideToggle().toggleClass(settings.classOpen);
if ($(this).next().hasClass(settings.classOpen)) {
$(this).children().html(settings.close).removeClass(settings.rlOpen).addClass(settings.rlClose);
} else {
$(this).children().html(settings.open).removeClass(settings.rlClose).addClass(settings.rlOpen);
}
});
});
}
};
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.collapse ');
}
};
})(jQuery);
$(function() {
$("#collapse").collapse('single', {});
});
#wrapper {
margin: 0 auto;
position: relative;
max-width: 640px;
}
.collapse > h3 {
background-color: #007197;
color: #fff;
margin: 0 auto;
padding: 3%;
text-decoration: none;
}
.collapse > h3 > span {
float: right;
}
.collapse > h3 + div {
display: none;
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<main class="main-wrapper">
<div id="collapse">
<h3 style="background:black;">One</h3>
<div style="background:red;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto illo velit temporibus aliquam eius dolorem dolor laudantium quidem porro obcaecati nesciunt ducimus doloribus molestiae ad praesentium reiciendis enim eligendi fugit!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quis delectus ducimus quibusdam ex totam natus sint nemo nam possimus explicabo labore architecto magnam accusantium veritatis tenetur repudiandae ab laboriosam?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis molestiae molestias atque asperiores illum nisi saepe placeat deleniti commodi dolore cupiditate quas. Ipsum odio quibusdam nemo est ducimus ea nesciunt?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga eligendi ex aperiam facilis alias! Quaerat asperiores quia molestias laboriosam commodi aspernatur dolorum nostrum impedit perspiciatis cupiditate quas distinctio earum dignissimos.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi laboriosam voluptates eum vero iste enim quas a nulla consequuntur quasi. Dolorum minima corporis molestias blanditiis ducimus obcaecati necessitatibus excepturi magnam?</p>
</div>
<h3 style="background:red;">Two</h3>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto illo velit temporibus aliquam eius dolorem dolor laudantium quidem porro obcaecati nesciunt ducimus doloribus molestiae ad praesentium reiciendis enim eligendi fugit!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quis delectus ducimus quibusdam ex totam natus sint nemo nam possimus explicabo labore architecto magnam accusantium veritatis tenetur repudiandae ab laboriosam?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis molestiae molestias atque asperiores illum nisi saepe placeat deleniti commodi dolore cupiditate quas. Ipsum odio quibusdam nemo est ducimus ea nesciunt?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga eligendi ex aperiam facilis alias! Quaerat asperiores quia molestias laboriosam commodi aspernatur dolorum nostrum impedit perspiciatis cupiditate quas distinctio earum dignissimos.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi laboriosam voluptates eum vero iste enim quas a nulla consequuntur quasi. Dolorum minima corporis molestias blanditiis ducimus obcaecati necessitatibus excepturi magnam?</p>
</div>
<h3 style="background:orange;">Three</h3>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto illo velit temporibus aliquam eius dolorem dolor laudantium quidem porro obcaecati nesciunt ducimus doloribus molestiae ad praesentium reiciendis enim eligendi fugit!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quis delectus ducimus quibusdam ex totam natus sint nemo nam possimus explicabo labore architecto magnam accusantium veritatis tenetur repudiandae ab laboriosam?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis molestiae molestias atque asperiores illum nisi saepe placeat deleniti commodi dolore cupiditate quas. Ipsum odio quibusdam nemo est ducimus ea nesciunt?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga eligendi ex aperiam facilis alias! Quaerat asperiores quia molestias laboriosam commodi aspernatur dolorum nostrum impedit perspiciatis cupiditate quas distinctio earum dignissimos.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi laboriosam voluptates eum vero iste enim quas a nulla consequuntur quasi. Dolorum minima corporis molestias blanditiis ducimus obcaecati necessitatibus excepturi magnam?</p>
</div>
<h3 style="background:blue;">Four</h3>
<div style="background:red;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto illo velit temporibus aliquam eius dolorem dolor laudantium quidem porro obcaecati nesciunt ducimus doloribus molestiae ad praesentium reiciendis enim eligendi fugit!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quis delectus ducimus quibusdam ex totam natus sint nemo nam possimus explicabo labore architecto magnam accusantium veritatis tenetur repudiandae ab laboriosam?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis molestiae molestias atque asperiores illum nisi saepe placeat deleniti commodi dolore cupiditate quas. Ipsum odio quibusdam nemo est ducimus ea nesciunt?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga eligendi ex aperiam facilis alias! Quaerat asperiores quia molestias laboriosam commodi aspernatur dolorum nostrum impedit perspiciatis cupiditate quas distinctio earum dignissimos.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi laboriosam voluptates eum vero iste enim quas a nulla consequuntur quasi. Dolorum minima corporis molestias blanditiis ducimus obcaecati necessitatibus excepturi magnam?</p>
</div>
<h3 style="background:green;">Five</h3>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto illo velit temporibus aliquam eius dolorem dolor laudantium quidem porro obcaecati nesciunt ducimus doloribus molestiae ad praesentium reiciendis enim eligendi fugit!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quis delectus ducimus quibusdam ex totam natus sint nemo nam possimus explicabo labore architecto magnam accusantium veritatis tenetur repudiandae ab laboriosam?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis molestiae molestias atque asperiores illum nisi saepe placeat deleniti commodi dolore cupiditate quas. Ipsum odio quibusdam nemo est ducimus ea nesciunt?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga eligendi ex aperiam facilis alias! Quaerat asperiores quia molestias laboriosam commodi aspernatur dolorum nostrum impedit perspiciatis cupiditate quas distinctio earum dignissimos.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi laboriosam voluptates eum vero iste enim quas a nulla consequuntur quasi. Dolorum minima corporis molestias blanditiis ducimus obcaecati necessitatibus excepturi magnam?</p>
</div>
</div>
</main>
</div>
You are seeing the effects of collapsing margins between your p elements and the adjacent h3 headers.
You can prevent this by simply adding the following CSS rule:
.collapse div {
overflow: auto;
}
See demo: https://jsfiddle.net/vauxjg7r/
Fiddle demo here.
Try to add this CSS style:
.collapse p {
margin: 0px;
}
But if you want to keep the space above, you can do:
.collapse p {
margin: 0px;
padding: 10px 0 0;
}
The issue was caused by browser-applied styles, you need to overwrite them with codes like above. Or, you could use CSS resets to normalize browser styles.
It's the margin from the paragraphs. You must overwrite the user agent stylesheet by adding this to your stylesheet:
p {
margin: 0;
padding: .5em 0;
}
This is due to margin collapsing on the p elements.
If there is no border, padding, inline content, or clearance to
separate the margin-top of a block with the margin-top of its first
child block, or no border, padding, inline content, height,
min-height, or max-height to separate the margin-bottom of a block
with the margin-bottom of its last child, then those margins collapse.
The collapsed margin ends up outside the parent.
(https://developer.mozilla.org/en-US/docs/Web/CSS/margin_collapsing)
To stop this effect from happening add overflow: hidden; to .collapse > h3 + div.
(function($) {
$.fn.collapse = function(method, options) {
var settings = $.extend({
collapse: "collapse",
signTag: "<span></span>",
titles: "h3",
titlesChild: "span",
container: "div",
classOpen: "opened",
open: "+",
close: "−",
rlOpen: "rl-open",
rlClose: "rl-close"
}, options);
var $element = $(this).children(settings.titles);
var $symbols = $(settings.signTag);
var $signOpen = $symbols.html(settings.open);
var $signClose = $symbols.html(settings.close);
var $insertElement = $symbols.appendTo($element);
$element.parent().addClass(settings.collapse);
if ($element.next().hasClass(settings.classOpen)) {
$element.children().html(settings.close).addClass(settings.rlClose);
} else {
$element.children().html(settings.open).addClass(settings.rlOpen);
}
var methods = {
single: function() {
return this.each(function() {
$(this).find(settings.container).eq(settings.childNum).addClass(settings.classOpen).slideDown()
.prev().children().html(settings.close).removeClass(settings.rlOpen).addClass(settings.rlClose);
$element.on('click', function() {
$(this).next().slideToggle().toggleClass(settings.classOpen);
if ($(this).next().hasClass(settings.classOpen)) {
$(this).children().html(settings.close).removeClass(settings.rlOpen).addClass(settings.rlClose);
} else {
$(this).children().html(settings.open).removeClass(settings.rlClose).addClass(settings.rlOpen);
}
});
});
}
};
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.collapse ');
}
};
})(jQuery);
$(function() {
$("#collapse").collapse('single', {});
});
#wrapper {
margin: 0 auto;
position: relative;
max-width: 640px;
}
.collapse > h3 {
background-color: #007197;
color: #fff;
margin: 0 auto;
padding: 3%;
text-decoration: none;
}
.collapse > h3 > span {
float: right;
}
.collapse > h3 + div {
display: none;
margin: 0;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<main class="main-wrapper">
<div id="collapse">
<h3 style="background:black;">One</h3>
<div style="background:red;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto illo velit temporibus aliquam eius dolorem dolor laudantium quidem porro obcaecati nesciunt ducimus doloribus molestiae ad praesentium reiciendis enim eligendi fugit!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quis delectus ducimus quibusdam ex totam natus sint nemo nam possimus explicabo labore architecto magnam accusantium veritatis tenetur repudiandae ab laboriosam?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis molestiae molestias atque asperiores illum nisi saepe placeat deleniti commodi dolore cupiditate quas. Ipsum odio quibusdam nemo est ducimus ea nesciunt?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga eligendi ex aperiam facilis alias! Quaerat asperiores quia molestias laboriosam commodi aspernatur dolorum nostrum impedit perspiciatis cupiditate quas distinctio earum dignissimos.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi laboriosam voluptates eum vero iste enim quas a nulla consequuntur quasi. Dolorum minima corporis molestias blanditiis ducimus obcaecati necessitatibus excepturi magnam?</p>
</div>
<h3 style="background:red;">Two</h3>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto illo velit temporibus aliquam eius dolorem dolor laudantium quidem porro obcaecati nesciunt ducimus doloribus molestiae ad praesentium reiciendis enim eligendi fugit!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quis delectus ducimus quibusdam ex totam natus sint nemo nam possimus explicabo labore architecto magnam accusantium veritatis tenetur repudiandae ab laboriosam?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis molestiae molestias atque asperiores illum nisi saepe placeat deleniti commodi dolore cupiditate quas. Ipsum odio quibusdam nemo est ducimus ea nesciunt?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga eligendi ex aperiam facilis alias! Quaerat asperiores quia molestias laboriosam commodi aspernatur dolorum nostrum impedit perspiciatis cupiditate quas distinctio earum dignissimos.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi laboriosam voluptates eum vero iste enim quas a nulla consequuntur quasi. Dolorum minima corporis molestias blanditiis ducimus obcaecati necessitatibus excepturi magnam?</p>
</div>
<h3 style="background:orange;">Three</h3>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto illo velit temporibus aliquam eius dolorem dolor laudantium quidem porro obcaecati nesciunt ducimus doloribus molestiae ad praesentium reiciendis enim eligendi fugit!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quis delectus ducimus quibusdam ex totam natus sint nemo nam possimus explicabo labore architecto magnam accusantium veritatis tenetur repudiandae ab laboriosam?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis molestiae molestias atque asperiores illum nisi saepe placeat deleniti commodi dolore cupiditate quas. Ipsum odio quibusdam nemo est ducimus ea nesciunt?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga eligendi ex aperiam facilis alias! Quaerat asperiores quia molestias laboriosam commodi aspernatur dolorum nostrum impedit perspiciatis cupiditate quas distinctio earum dignissimos.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi laboriosam voluptates eum vero iste enim quas a nulla consequuntur quasi. Dolorum minima corporis molestias blanditiis ducimus obcaecati necessitatibus excepturi magnam?</p>
</div>
<h3 style="background:blue;">Four</h3>
<div style="background:red;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto illo velit temporibus aliquam eius dolorem dolor laudantium quidem porro obcaecati nesciunt ducimus doloribus molestiae ad praesentium reiciendis enim eligendi fugit!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quis delectus ducimus quibusdam ex totam natus sint nemo nam possimus explicabo labore architecto magnam accusantium veritatis tenetur repudiandae ab laboriosam?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis molestiae molestias atque asperiores illum nisi saepe placeat deleniti commodi dolore cupiditate quas. Ipsum odio quibusdam nemo est ducimus ea nesciunt?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga eligendi ex aperiam facilis alias! Quaerat asperiores quia molestias laboriosam commodi aspernatur dolorum nostrum impedit perspiciatis cupiditate quas distinctio earum dignissimos.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi laboriosam voluptates eum vero iste enim quas a nulla consequuntur quasi. Dolorum minima corporis molestias blanditiis ducimus obcaecati necessitatibus excepturi magnam?</p>
</div>
<h3 style="background:green;">Five</h3>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto illo velit temporibus aliquam eius dolorem dolor laudantium quidem porro obcaecati nesciunt ducimus doloribus molestiae ad praesentium reiciendis enim eligendi fugit!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quis delectus ducimus quibusdam ex totam natus sint nemo nam possimus explicabo labore architecto magnam accusantium veritatis tenetur repudiandae ab laboriosam?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis molestiae molestias atque asperiores illum nisi saepe placeat deleniti commodi dolore cupiditate quas. Ipsum odio quibusdam nemo est ducimus ea nesciunt?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga eligendi ex aperiam facilis alias! Quaerat asperiores quia molestias laboriosam commodi aspernatur dolorum nostrum impedit perspiciatis cupiditate quas distinctio earum dignissimos.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi laboriosam voluptates eum vero iste enim quas a nulla consequuntur quasi. Dolorum minima corporis molestias blanditiis ducimus obcaecati necessitatibus excepturi magnam?</p>
</div>
</div>
</main>
</div>

Categories

Resources