I am trying to trigger this code each time someone scrolls to that section, the code works fine because it does trigger but it only does it once. I am trying to think of the easiest way to make it trigger every time someone scrolls to that section. I tried taking off the !viewed from the condition and it does trigger but the countdown then goes backwards, not really sure why.
This is the code I have but only triggers once.
<script>
var viewed = false;
function isScrolledIntoView(elem) {
var docViewTop = jQuery(window).scrollTop();
var docViewBottom = docViewTop + jQuery(window).height();
var elemTop = jQuery(elem).offset().top;
var elemBottom = elemTop + jQuery(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
function testScroll() {
if (isScrolledIntoView(jQuery(".numbers")) && !viewed) {
jQuery('.value').each(function () {
jQuery(this).prop('Counter',0).animate({
Counter: jQuery(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
jQuery(this).text(Math.ceil(now));
}
});
});
}
}
</script>
Here is the link to my current code.
https://codepen.io/fjadvocates/pen/PoeKWbq
Consider the following.
jQuery(function($) {
var viewed = false;
function isScrolledIntoView(elem) {
var inView = false;
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + ($(elem).height() / 2);
inView = (elemTop >= docViewTop) && (elemBottom < docViewBottom);
return inView;
}
function testScroll() {
console.log("Scroll Event", $(window).scrollTop());
if (isScrolledIntoView($(".numbers"))) {
console.log("Numbers in View");
if (viewed == false) {
console.log("Not Viewed.");
viewed = true;
$('.value').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now));
}
});
});
}
}
}
$(window).scroll(testScroll);
});
.bigblock {
height: 800px;
background: red;
color: white;
font-size: xx-large;
text-align: center;
}
.bigblock p {
font-size: x-large;
}
.numbers {
padding: 40px 0;
}
.numbers .flex {
flex-wrap: wrap;
justify-content: space-between;
}
.numbers .number-item {
width: 45%;
padding: 20px 0;
text-align: center;
font-size: 1.4em;
}
.numbers .number-item h2 {
font-weight: 500;
}
.numbers .number-item h6 {
font-weight: 300;
text-transform: uppercase;
font-size: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bigblock">
Scroll Down.<br>
<p>The Idea is to scroll down then it triggers but when you scroll out of it and come back to the same section, it should trigger again, from 0 to whatever the value was originally.</p>
</div>
<section id="wegetresults-hp" class="container-fluid text-center blueish-bg numbers">
<hr class="line w-25 d-block mx-auto">
<div class="row d-flex justify-content-center py-5 ">
<div class="col-md col-sm-6 number-item">
<span class="counter">$</span> <span class="counter value ">500</span>
<p>Millions recovered for clients.</p>
</div>
<div class="col-md col-sm-6 number-item">
<span class="counter value ">20</span>
<p>Offices and counting</p>
</div>
</div>
<div class="row d-flex justify-content-center py-5 ">
<div class="col-md col-sm-6 number-item">
<span class="counter value ">50000</span>
<p>Clients helped</p>
</div>
<div class="col-md col-sm-6 number-item">
<span class="counter value ">200</span>
<p>Team members committed to you</p>
</div>
</div>
</section>
The primary issue is your logic. Since .numbers was the last element, the window could not scroll far enough to overcome the height needed to be true. If you reduce the height by half, the element is largely in view. Obviously, you can adjust as needed.
I have three div's in the following code.
<div id="wrap">
<div id="outer">
<div id="inner">
</div>
</div>
</div>
Here "inner" div is moving with mouseMove event. How can I move "outer" div along with "inner" div when "inner" div touches the top and left of "outer" div but "outer" div should not move when "inner" div inside or don't touch "outer" div?
var innerDiv = $('#inner');
var outerDiv = $('#outer');
var outDim = outerDiv.offset();
outDim.right = (outDim.left + outerDiv.width());
outDim.bottom = (outDim.top + outerDiv.height());
$(document).on('mousemove', function(e) {
var x = (e.clientX) - 15;
var y = (e.clientY) - 15;
var x_allowed = x >= outDim.left && x <= (outDim.right - innerDiv.width());
var y_allowed = y >= outDim.top && y <= (outDim.bottom - innerDiv.height());
if (y_allowed) {
innerDiv.css({
top: y + 'px',
});
} else {
//fine tune tweaks
if (y >= outDim.top) {
innerDiv.css({
top: (outDim.bottom - innerDiv.height()) + 'px',
});
}
if (y <= (outDim.bottom - innerDiv.height())) {
innerDiv.css({
top: outDim.top + 'px',
});
}
}
if (x_allowed) {
innerDiv.css({
left: x + 'px'
});
} else {
//fine tune tweaks
if (x >= outDim.left) {
innerDiv.css({
left: outDim.right - innerDiv.width() + 'px',
});
}
if (x <= (outDim.right - innerDiv.width())) {
innerDiv.css({
left: outDim.left + 'px',
});
}
}
});
#wrap {
height: 200px;
width: 200px;
border: 2px solid black;
}
#outer {
height: 100px;
width: 100px;
border: 2px solid blue;
margin: 0 auto;
}
#inner {
height: 40px;
width: 40px;
border: 2px solid red;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap">
<div id="outer">
<div id="inner">
</div>
</div>
</div>
Fiddle link
I want to change the active starting item to 3 instead of 1s. In short instead of number 1s is active. I want to change it to number 3 staring item or anything if I add active on a class. How Can I achieve that stuff. I'm all over the internet but nothing happens.
Please see below sample of my code html and javascript.
//Small carosel code set here
$(document).ready(function() { ResCarouselOnInit(); });
$(window).resize(function() {
var r = new Date();
setTimeout(function() {
ResCarouselResize(r);
}, 200);
});
function ResCarouselOnInit() {
ResCarouselSize();
$(document).on('click', '.leftRs, .rightRs', function() {
ResCarousel(this);
});
$(document).on("mouseenter", ".ResHover", function() {
$(this).addClass("ResHovered");
});
$(document).on("mouseleave", ".ResHover", function() {
$(this).removeClass("ResHovered");
});
}
// Rescarousel Auto Slide
function ResCarouselSlide(e) {
var thiss = $(e).find(".rightRs");
var dataInterval = $(e).attr('data-interval');
!isNaN(dataInterval) && $(e).addClass("ResHover") && setInterval(function() {
!(thiss.parent().hasClass("ResHovered")) && ResCarousel(thiss);
}, +(dataInterval));
}
function ResCarouselResize() {
function myfunction() {
console.log("resize Works");
//var r = $('body').width();
$('.resCarousel').each(function() {
var divValue = $(this).attr('data-value');
var itemWidth = $(this).find('.item').width();
$(this).find(".resCarousel-inner").scrollLeft(divValue * itemWidth);
//var itemsSplit = $(this).attr("data-items").split(',');
//var it = r >= 1200 ? itemsSplit[3] : r >= 992 ? itemsSplit[2] : r >= 768 ? itemsSplit[1] : itemsSplit[0];
//$(this).attr("data-itm", it);
});
}
//var ResTimeout = setTimeout(function() { myfunction() }, 3000);
//clearTimeout(ResTimeout);
//ResTimeout = setTimeout(function() { myfunction() }, 3000);
//console.log(ResTimeout);
myfunction();
}
//this function define the size of the items
function ResCarouselSize() {
var t0 = performance.now();
// styleCollector0 = styleCollector1 = styleCollector2 = styleCollector3 = "";
$('.resCarousel').each(function(index) {
var itemsSplit = $(this).attr("data-items").split('-');
$(this).addClass("ResSlid" + index);
for (var i = 0; i < 4; i++) {
if (i == 0) {
var styleCollector0 = ".ResSlid" + index + " .item {width: " + 100 / itemsSplit[i] + "%}";
} else if (i == 1) {
var styleCollector1 = ".ResSlid" + index + " .item {width: " + 100 / itemsSplit[i] + "%}";
} else if (i == 2) {
var styleCollector2 = ".ResSlid" + index + " .item {width: " + 100 / itemsSplit[i] + "%}";
} else if (i == 3) {
var styleCollector3 = ".ResSlid" + index + " .item {width: " + 100 / itemsSplit[i] + "%}";
}
}
$(this).attr("data-value", "0");
//var r = $('body').width();
//var it = r >= 1200 ? itemsSplit[3] : r >= 992 ? itemsSplit[2] : r >= 768 ? itemsSplit[1] : itemsSplit[0];
//$(this).attr("data-itm", it);
var styleCollector = "#media (max-width:767px){" + styleCollector0 + "}" +
"#media (min-width:768px){" + styleCollector1 + "}" +
"#media (min-width:992px){" + styleCollector2 + "}" +
"#media (min-width:1200px){" + styleCollector3 + "}";
//$(this).append("<div class=\"ResStyleManager\"></div>")
$(this).find("style").remove();
$(this).append("<style>" + styleCollector + "</style>");
ResCarouselSlide(this);
});
//console.log(styleCollector);
//$("body").append("<div class=\"ResStyleManager\"></div>")
//$('.ResStyleManager').html(null).append("<style>" + styleCollector + "</style>");
var t1 = performance.now();
console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to Size');
}
//this function used to move the items
function ResCarousel(Btn) {
//var t0 = performance.now();
var parent = $(Btn).parent(),
slide = +parent.attr("data-slide"),
itemsDiv = parent.find('.resCarousel-inner'),
//divValueq = +parent.attr('data-value'),
itemSpeed = +parent.attr("data-speed"),
itemLoad = +parent.attr("data-load"),
//animi = parent.attr("data-animator"),
translateXval = '',
currentSlide = "",
itemLenght = itemsDiv.find(".item").length,
itemWidth = itemsDiv.find('.item').outerWidth(),
dataItm = +Math.round(itemsDiv.outerWidth() / itemWidth),
cond = $(Btn).hasClass("leftRs"),
divValue = Math.round(itemsDiv.scrollLeft() / itemWidth);
//console.log(dataItm + "," + Math.abs(dataItmq));
//console.log(divValue + "," + divValueq);
//console.log(cond);
//console.log(typeof + parent.attr("data-slide"))
itemSpeed = !isNaN(itemSpeed) ? itemSpeed : 400;
slide = slide < dataItm ? slide : dataItm;
if (cond) {
currentSlide = divValue - slide;
translateXval = currentSlide * itemWidth;
var MoveSlide = currentSlide + slide;
//console.log(itemloop);
if (divValue == 0) {
currentSlide = itemLenght - slide;
translateXval = currentSlide * itemWidth;
currentSlide = itemLenght - dataItm;
itemSpeed = 400;
//console.log(currentSlide + "," + translateXval);
} else if (slide >= MoveSlide) {
currentSlide = translateXval = 0;
}
} else {
currentSlide = divValue + slide;
translateXval = currentSlide * itemWidth;
var MoveSlide = currentSlide + slide;
//console.log(itemLenght + "," + (MoveSlide + "," + slide + "," + dataItm));
//console.log(itemLenght + "," + (MoveSlide - slide + dataItm));
//console.log((divValue + dataItm) + "," + itemLenght);
if (divValue + dataItm == itemLenght) {
currentSlide = translateXval = 0;
itemSpeed = 400;
} else if (itemLenght <= (MoveSlide - slide + dataItm)) {
currentSlide = itemLenght - slide;
translateXval = currentSlide * itemWidth;
currentSlide = itemLenght - dataItm;
}
// resCarouselAnimator(itemsDiv, currentSlide + 1, currentSlide + slide);
}
//console.log(slide + "," + itemWidth);
parent.attr("data-animator") == "lazy" && resCarouselAnimator(itemsDiv, cond ? 0 : 1, currentSlide + 1, currentSlide + dataItm, itemSpeed, (slide * itemWidth));
//console.log(itemsDiv.scrollLeft() + "," + translateXval)
//console.log(itemSpeed);
if (!isNaN(itemLoad)) {
itemLoad = itemLoad >= slide ? itemLoad : slide;
//console.log((itemLenght - itemLoad) <= currentSlide + dataItm);
//console.log((itemLenght - itemLoad) + " ," + (currentSlide + dataItm) + " ," + (itemLenght - dataItm));
(itemLenght - itemLoad) <= (currentSlide + dataItm) && ResCarouselLoad1(itemsDiv);
}
itemsDiv.animate({ scrollLeft: translateXval }, itemSpeed);
parent.attr("data-value", currentSlide);
//var t1 = performance.now();
//console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to generate');
}
function ResCarouselLoad1(e) {
//console.log(e.attr("id"));
$("#" + e.attr("id")).trigger("ResCarouselLoad");
}
function resCarouselAnimator(parent, direction, start, end, speed, length) {
//console.log(parent + "," + start + "," + end);
var val = 5;
if (direction == 0) {
for (var i = start - 1; i < end + 1; i++) {
val = val * 2;
}
val = -val;
}
//console.log(length);
//if (direction == 1) {
// for (var i = start - 1; i < end + 1; i++) {
// length = length / 2
// console.log(length);
// }
// //val = val;
//}
//val = direction == 1 ? length : -length;
for (var i = start - 1; i < end; i++) {
val = direction == 0 ? val / 2 : val * 2;
//console.log(val);
//console.log(parent.find(".item").eq(i).find("h1").text());
parent.find(".item").eq(i).css("transform", "translateX(" + val + "px)");
}
setTimeout(function() {
parent.find(".item").attr("style", "");
}, speed - 70);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>ResCarousel</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<style>
body {
font-family: 'Trirong', serif;
background: #eee;
}
.p0 {
padding: 0;
}
.resCarousel-inner .item {
/*border: 4px solid #eee;*/
/*vertical-align: top;*/
text-align: center;
}
.resCarousel-inner .item .tile div,
.banner .item div {
display: table;
width: 100%;
min-height: 250px;
text-align: center;
/*box-shadow: 0 1px 1px rgba(0, 0, 0, .1);*/
}
.resCarousel-inner .item h1 {
display: table-cell;
vertical-align: middle;
color: white;
}
.banner .item div {
background: url('demoImg.jpg') center top no-repeat;
background-size: cover;
min-height: 550px;
}
.item .tile div {
background: url('demoImg.jpg') center center no-repeat;
background-size: cover;
height: 200px;
color: white;
}
.item div h1 {
background: rgba(0, 0, 0, .4);
}
/*resCarousel Css*/
.outt {
display: none;
}
.leftRs {
position: absolute;
margin: auto;
top: 0;
bottom: 0;
z-index: 100;
left: 0;
width: 50px;
height: 50px;
box-shadow: 1px 2px 10px -1px rgba(0, 0, 0, .3);
border-radius: 999px;
}
.rightRs {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
z-index: 100;
width: 50px;
height: 50px;
box-shadow: 1px 2px 10px -1px rgba(0, 0, 0, .3);
border-radius: 999px;
}
.resCarousel {
/*float: left;
overflow: hidden;*/
width: 100%;
position: relative;
}
.resCarousel-inner {
overflow-x: hidden;
white-space: nowrap;
font-size: 0;
vertical-align: top;
}
.resCarousel-inner .item {
display: inline-block;
font-size: 14px;
white-space: initial;
}
/*banner*/
.banner {
overflow: hidden !important;
}
/*tile css*/
.resCarousel-inner .item .tile {
background: white;
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
margin: 5px;
}
/*animation*/
.resCarousel[data-animator="lazy"] .item {
transition: .6s ease all;
}
#media (max-width: 767px) {
.leftRs,
.rightRs {
/*display: none;*/
}
.resCarousel-inner {
overflow-x: auto;
}
}
/*resCarousel Css End*/
</style>
</head>
<body>
<!-- test -->
<!--home-->
<div class="container p8">
<div class="resCarousel carousel" id="puta" data-type="multi" data-items="2-4-4-4" data-slide="4" data-interval="false" data-value="8">
<div class="resCarousel-inner">
<div class="item">
<div class="tile">
<div>
<h1>1s</h1>
</div>
<h3>Title</h3>
<p>content</p>
</div>
</div>
<div class="item">
<div class="tile">
<div>
<h1>2</h1>
</div>
<h3>Title</h3>
<p>content</p>
</div>
</div>
<div class="item active">
<div class="tile">
<div>
<h1>3</h1>
</div>
<h3>Title</h3>
<p>content</p>
</div>
</div>
<div class="item">
<div class="tile">
<div>
<h1>4</h1>
</div>
<h3>Title</h3>
<p>content</p>
</div>
</div>
<div class="item">
<div class="tile">
<div>
<h1>5</h1>
</div>
<h3>Title</h3>
<p>content</p>
</div>
</div>
<div class="item">
<div class="tile">
<div>
<h1>6</h1>
</div>
<h3>Title</h3>
<p>content</p>
</div>
</div>
<div class="item">
<div class="tile">
<div>
<h1>7</h1>
</div>
<h3>Title</h3>
<p>content</p>
</div>
</div>
<div class="item">
<div class="tile">
<div>
<h1>8</h1>
</div>
<h3>Title</h3>
<p>content</p>
</div>
</div>
<div class="item">
<div class="tile">
<div>
<h1>9</h1>
</div>
<h3>Title</h3>
<p>content</p>
</div>
</div>
<div class="item">
<div class="tile">
<div>
<h1>10</h1>
</div>
<h3>Title</h3>
<p>content</p>
</div>
</div>
<div class="item">
<div class="tile">
<div>
<h1>11</h1>
</div>
<h3>Title</h3>
<p>content</p>
</div>
</div>
<div class="item">
<div class="tile">
<div>
<h1>12</h1>
</div>
<h3>Title</h3>
<p>content</p>
</div>
</div>
<div class="item">
<div class="tile">
<div>
<h1>13</h1>
</div>
<h3>Title</h3>
<p>content</p>
</div>
</div>
<div class="item">
<div class="tile">
<div>
<h1>14</h1>
</div>
<h3>Title</h3>
<p>content</p>
</div>
</div>
</div>
<button class='btn btn-default leftRs'><</button>
<button class='btn btn-default rightRs'>></button>
</div>
</div>
<hr>
<script src="js/resCarousel.js"></script>
</body>
</html>
U use this script for spreading imgs inside div, without any overlapping.
Result is good but it's too slow. How can I accelerate this?
I mean, sometimes my browser is crashing because input positions of images are "bad".
CSS
.gallery{
position:relative;
background: red;
width: 700px;
height: 600px;
}
.picture{
border:1px solid #000;
margin: 5px 5px 5px 5px;
position:absolute;
}
JS
$(document).ready(function() {
var containerW = 700;
var containerH = 600;
var positions = [];
$('.picture').each(function() {
var coords = {
w: $(this).outerWidth(true),
h: $(this).outerHeight(true)
};
var success = false;
while (!success) {
coords.x = parseInt(Math.random() * (containerW-coords.w));
coords.y = parseInt(Math.random() * (containerH-coords.h));
var success = true;
$.each(positions, function(){
if (
coords.x <= (this.x + this.w) &&
(coords.x + coords.w) >= this.x &&
coords.y <= (this.y + this.h) &&
(coords.y + coords.h) >= this.y
) {
success = false;
}
});
}
positions.push(coords);
$(this).css({
top: coords.y + 'px',
left: coords.x + 'px'
});
});
});
HTML
<div class='container'>
<div class='gallery'>
<div class='picture'><img src='http://lionssharedigital.com/wp-content/uploads/2013/08/apple-logo-small-150x150.jpg'/></div>
<div class='picture'><img src='http://lionssharedigital.com/wp-content/uploads/2013/08/apple-logo-small-150x150.jpg'/></div>
<div class='picture'><img src='http://lionssharedigital.com/wp-content/uploads/2013/08/apple-logo-small-150x150.jpg'/></div>
<div class='picture'><img src='http://lionssharedigital.com/wp-content/uploads/2013/08/apple-logo-small-150x150.jpg'/></div>
<div class='picture'><img src='http://lionssharedigital.com/wp-content/uploads/2013/08/apple-logo-small-150x150.jpg'/></div>
<div class='picture'><img src='http://lionssharedigital.com/wp-content/uploads/2013/08/apple-logo-small-150x150.jpg'/></div>
</div>
</div>
You could use while(parameter--) to clamp the maximum amount of calculations.
$(document).ready(function() {
var containerW = 700;
var containerH = 600;
var positions = [];
$('.picture').each(function() {
$(this).hide();
var coords = {
w: $(this).outerWidth(true),
h: $(this).outerHeight(true)
};
var success = 100;
while (success--) {
coords.x = parseInt(Math.random() * (containerW - coords.w));
coords.y = parseInt(Math.random() * (containerH - coords.h));
var passed = true;
$.each(positions, function() {
if (
coords.x <= (this.x + this.w) &&
(coords.x + coords.w) >= this.x &&
coords.y <= (this.y + this.h) &&
(coords.y + coords.h) >= this.y
) {
passed = false;
}
});
if (passed) {
console.log(success)
break;
}
}
positions.push(coords);
$(this).css({
top: coords.y + 'px',
left: coords.x + 'px'
});
$(this).show();
});
});
.gallery {
position: relative;
background: red;
width: 700px;
height: 600px;
}
.picture {
border: 1px solid #000;
margin: 5px 5px 5px 5px;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<div class='gallery'>
<div class='picture'><img src='http://lionssharedigital.com/wp-content/uploads/2013/08/apple-logo-small-150x150.jpg' /></div>
<div class='picture'><img src='http://lionssharedigital.com/wp-content/uploads/2013/08/apple-logo-small-150x150.jpg' /></div>
<div class='picture'><img src='http://lionssharedigital.com/wp-content/uploads/2013/08/apple-logo-small-150x150.jpg' /></div>
<div class='picture'><img src='http://lionssharedigital.com/wp-content/uploads/2013/08/apple-logo-small-150x150.jpg' /></div>
<div class='picture'><img src='http://lionssharedigital.com/wp-content/uploads/2013/08/apple-logo-small-150x150.jpg' /></div>
<div class='picture'><img src='http://lionssharedigital.com/wp-content/uploads/2013/08/apple-logo-small-150x150.jpg' /></div>
</div>
</div>
Find below image reference:
What I want exactly is when only one section (section4) comes in window view around 40% - 80%. On scroll stop the section4 should auto scroll to fit on window.
Here, The basic fiddle without any script.
body,
html {
height: 100%;
margin: 0;
}
.sections {
height: 100%;
background: #000;
opacity: 0.7;
}
#section2 {
background: #ccc;
}
#section3 {
background: #9c0;
}
#section4 {
background: #999;
}
#section4 {
background: #ddd;
}
<div class="sections" id="section1"></div>
<div class="sections" id="section2"></div>
<div class="sections" id="section3"></div>
<div class="sections" id="section4"></div>
<div class="sections" id="section5"></div>
I have tried jquery visible plugin but it didn't help. So I have put commented one.
/*
var ww = $(window).width();
$(window).scroll(function(){
if ($('#section3').visible(true)) {
$('body, html').animate({scrollTop: $('#section4').offset().top});
}else if($('#section5').visible(true)) {
$('body, html').animate({scrollTop: $('#section4').offset().top});
}
});
*/
Use script to compare the scrollTop of the screen with the offset().top and the height of the section.
Note that ratio determines how much the element is seen on the screen (greater that 0.6 is used to determine if more than 60% of the section is visible on screen).
See demo below with comments inline:
/*debouce (courtesy:underscore.js)*/
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
// scroll listener
$(window).scroll(debounce(function() {
var $window = $(window);
// change this to '.sections' if you want the effect for all sections
$('#section4').each(function() {
var top_of_element = $(this).offset().top;
var bottom_of_element = $(this).offset().top + $(this).outerHeight();
var bottom_of_screen = $window.scrollTop() + $window.height();
var top_of_screen = $window.scrollTop();
var height_of_element = $(this).outerHeight();
// if element below top of screen
if (top_of_element > top_of_screen && bottom_of_screen < bottom_of_element) {
var ratio = (bottom_of_screen - top_of_element) / height_of_element;
if (ratio > 0.6) {
// animate by scrolling up
$('body, html').animate({
scrollTop: $(this).offset().top
});
}
}
// if element above top of screen
else if (bottom_of_element > top_of_screen && bottom_of_screen > bottom_of_element) {
var ratio = (bottom_of_element - top_of_screen) / height_of_element;
if (ratio > 0.6) {
// animate by scrolling down
$('body, html').animate({
scrollTop: $(this).offset().top
});
}
}
});
}, 250));
body,
html {
height: 100%;
margin: 0;
}
.sections {
height: 100%;
background: #000;
opacity: 0.7;
}
#section2 {
background: #ccc;
}
#section3 {
background: #9c0;
}
#section4 {
background: #999;
}
#section4 {
background: #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sections" id="section1"></div>
<div class="sections" id="section2"></div>
<div class="sections" id="section3"></div>
<div class="sections" id="section4"></div>
<div class="sections" id="section5"></div>