Prevent shaking on hard scroll while animating scrollTop - javascript

I am scrolling section to section, but if I scroll harshly with the mouse (not just one easy scroll) or I scroll harshly on the laptop touchpad, it shakes up and down before the scrolling animation starts or even jumps 2 sections!
Is it possible to make it scroll smoothly and always one section only (not jump 2 sections) regardless of how hard someone scrolls and basically disable scrolling while the animation is taking place?
My code (JSFiddle):
var isAnimated = false;
var nbhdLength = $('.nbhd').length;
var lastSectionId = nbhdLength - 1;
var allHeight = (nbhdLength - 1) * window.innerHeight;
var up = true;
function setHeights() {
$('.nbhd').css('height', window.innerHeight);
}
setHeights();
$('html').mousewheel(function(e) {
var up = e.deltaY > 0;
if (up) {
console.log('up');
up = true;
} else {
console.log('down');
up = false;
// console.log(up);
}
if (!up && $('#id' + lastSectionId).hasClass('scrolledto') || (!up && !$('.scrolledto').length)) {
$('.scrolledto').removeClass('scrolledto');
return;
}
if (isAnimated) return;
isAnimated = true;
var currentSectionId = $('.nbhd.scrolledto').data('id');
up ? currentSectionId-- : currentSectionId++;
if (currentSectionId < 0) currentSectionId = 0;
if (!$('.scrolledto').length) currentSectionId = lastSectionId;
$('.scrolledto').removeClass('scrolledto');
var section = $('#id' + currentSectionId);
section.addClass('scrolledto');
var pos = section.offset().top;
$('body, html').animate({
scrollTop: pos
}, 1000, function() {
setTimeout(function() {
isAnimated = false;
}, 100)
console.log($(window).scrollTop());
});
});
.div {
width: 100%;
}
.red {
background: red;
}
.yellow {
background: yellow;
}
.green {
background: green;
}
.blue {
background: blue;
}
.abovefooter {
background: gray;
height: 200px;
}
.footer {
background: black;
height: 350px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>
<div id="id0" data-id="0" class="nbhd red scrolledto"></div>
<div id="id1" data-id="1" class="nbhd yellow"></div>
<div id="id2" data-id="2" class="nbhd green"></div>
<div id="id3" data-id="3" class="nbhd blue"></div>
<div class="abovefooter"></div>
<div class="footer"></div>

You need to prevent the default mouseWheel event from happening, using javascript to perform the desired effect instead.
$('html').mousewheel(function(e) {
e.preventDefault();
//...
}
Demo: https://jsfiddle.net/b67uw0cx/1/

Related

How to set top:0(offset:0) when image come in window viewport?

I want to set top:0(offset:0) when image come in viewport on single scroll (like on every single scroll next image set to top 0 of image position or offset 0 of image) after completing scrolling all image, continue scrolling the page. Any one have any idea, JavaScript code for this?
Here is link for try out JsFiddle
<div class="main-div">
<div class="sticky-div">
<img src="https://images.unsplash.com/photo-1601140958046-ce3c75269438?ixlib=rb-
1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2134&q=80" />
</div>
<div class="sticky-div">
<img src="https://images.unsplash.com/photo-1559642147-97be7782c7b3?ixlib=rb-
1.2.1&auto=format&fit=crop&w=700&q=80">
</div>
<div class="sticky-div">
<img src="https://images.unsplash.com/photo-1527435292159-ba44021581fa?ixlib=rb-
1.2.1&auto=format&fit=crop&w=634&q=80">
</div>
</div>
.main-div {
box-sizing: border-box;
}
.sticky-div {
position: sticky;
top:0;
height:100vh;
}
if($(window).width() >= 1024){
(function($) {
var selector = ".home-product-slider .product-item";
var $slides = $(selector);
var currentSlide = 0;
var isAnimating = false;
var stopAnimation = function() {
setTimeout(function() {
isAnimating = false;
}, );
};
var bottomIsReached = function($elem) {
var rect = $elem[0].getBoundingClientRect();
return rect.bottom <= $(window).height();
};
var topIsReached = function($elem) {
var rect = $elem[0].getBoundingClientRect();
return rect.top >= 0;
};
document.addEventListener(
"wheel",
function(event) {
var $currentSlide = $($slides[currentSlide]);
if (isAnimating) {
event.preventDefault();
return;
}
var direction = -event.deltaY;
if (direction < 0) {
// next
if (currentSlide + 1 >= $slides.length) return;
if (!bottomIsReached($currentSlide)) return;
event.preventDefault();
currentSlide++;
var $slide = $($slides[currentSlide]);
var offsetTop = $slide.offset().top;
isAnimating = false;
$("html, body").animate(
{
scrollTop: offsetTop,
behavior: 'smooth'
},
stopAnimation
);
} else {
// back
if (currentSlide - 1 < 0) return;
if (!topIsReached($currentSlide)) return;
event.preventDefault();
currentSlide--;
var $slide = $($slides[currentSlide]);
var offsetTop = $slide.offset().top;
isAnimating = false;
$("html, body").animate(
{
// scrollTop: offsetTop
},
stopAnimation
);
}
{ passive: false }
},
);
})(jQuery);
//home page slider script end here
}
You're looking for scroll snapping. On the container that controls the scrolling set the scroll-snap-type: y mandatory rule. Here you say that there should be snapped in the y axis and that the snap should be honored without exceptions.
On the elements that you want snapped, use the scroll-snap-align property. Set this to start indicating that the start of the element that scrolls into view should fall on the snap grid.
Do beware, the combination of position: sticky and scroll snapping could lead to buggy behavior on Safari iOS. source
html,
body {
margin: 0;
overflow: hidden;
}
.main-div {
box-sizing: border-box;
width: 1000px;
height: 100vh;
max-width: 100%;
overflow-y: auto;
scroll-snap-type: y mandatory;
}
.sticky-div {
position: sticky;
top: 0px;
width: 100%;
max-height: 100%;
height: 750px;
scroll-snap-align: start;
}
img {
width: 100%;
height: 100%;
object-fit: cover;
}
<div class="main-div">
<div class="sticky-div">
<img src="https://images.unsplash.com/photo-1601140958046-ce3c75269438?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2134&q=80" />
</div>
<div class="sticky-div">
<img src="https://images.unsplash.com/photo-1559642147-97be7782c7b3?ixlib=rb-1.2.1&auto=format&fit=crop&w=700&q=80">
</div>
<div class="sticky-div">
<img src="https://images.unsplash.com/photo-1527435292159-ba44021581fa?ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80">
</div>
<div class="sticky-div">
<img src="https://images.unsplash.com/photo-1601140958046-ce3c75269438?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2134&q=80" />
</div>
<div class="sticky-div">
<img src="https://images.unsplash.com/photo-1559642147-97be7782c7b3?ixlib=rb-1.2.1&auto=format&fit=crop&w=700&q=80">
</div>
<div class="sticky-div">
<img src="https://images.unsplash.com/photo-1527435292159-ba44021581fa?ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80">
</div>
</div>

css 100vh scroll stops after 3rd section

I'm trying to scroll by every section, it's working but it won't scroll to the last section just stops at the 3rd one and won't move down after that.
What am I doing wrong?
<div class="body" data-spy="scroll" data-target=".navbar-fixed-top">
<section id="red" class="bc1">
</section>
<section id="blue" class="bc2">
</section>
<section id="green" class="bc3">
</section>
<section id="blue" class="bc4">
</section>
</div>
<script>
var $pages = $('section'), tot = $pages.length, c = 0, pagePos = 0, down = 0, listen = true;
$('.body').on('DOMMouseScroll mousewheel', function(e) {
e.preventDefault();
if (!listen)
return;
listen = false;
down = e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0;
c = Math.min(Math.max(0, down ? ++c : --c), tot - 1);
pagePos = $pages.eq(c).offset().top;
$(this).stop().animate({
scrollTop : pagePos
}, 850, function() {
listen = true;
});
});
</script>
The problem is that offset measures the distance of the element from the top of the body. But once you have scrolled the offset is different since the elements have moved closer/further from the last scroll.
So in order to account for this you need to add the scrollTop() of the .body element.
Updated code
var $pages = $('section'),
tot = $pages.length,
c = 0,
pagePos = 0,
down = 0,
listen = true,
body = $('.body');
body.on('DOMMouseScroll mousewheel', function(e) {
e.preventDefault();
if (!listen)
return;
listen = false;
down = e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0;
c = Math.min(Math.max(0, down ? ++c : --c), tot - 1);
pagePos = $pages.eq(c).offset().top + body.scrollTop();
$(this).stop().animate({
scrollTop: pagePos
}, 850, function() {
listen = true;
});
});
html,
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.bc1,
.bc2,
.bc3,
.bc4 {
height: 100vh;
}
#red {
background: red;
}
#blue {
background: blue;
}
#green {
background: green;
}
.body {
height: 100vh;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body" data-spy="scroll" data-target=".navbar-fixed-top">
<section id="red" class="bc1"></section>
<section id="blue" class="bc2"></section>
<section id="green" class="bc3"></section>
<section id="blue" class="bc4"></section>
</div>

Snap to scroll in scroll stop

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>

Detect when an image enters a div?

I am creating a maze game, and I want to detect when the image following the cursor reaches a certain div, the finishing point. I have the image following the mouse, and I have the container that the image will be in. When the image reaches the div, I want something to trigger, lets say an alert. How can I achieve this?
var startMove;
$(document).mousemove(function(e) {
var DIFF_SNAP = 10;
var DIFF_UNSNAP = 100;
var difLeft = $('#image').offset().left - e.pageX;
var difTop = $('#image').offset().top - e.pageY;
if (!startMove && Math.abs(difLeft) < DIFF_SNAP && Math.abs(difTop) < DIFF_SNAP) {
startMove = true;
$('html').removeClass('showCursor');
} else if (startMove && !(Math.abs(difLeft) < DIFF_UNSNAP && Math.abs(difTop) < DIFF_UNSNAP)) {
startMove = false;
}
if (startMove) {
$("#image").css({
left: e.pageX,
top: e.pageY
});
} else {
$('html').addClass('showCursor');
}
});
$(document).mouseleave(function() {
startMove = false;
})
html {cursor: none;}
html.showCursor{cursor: default;}
#image{
position:absolute;
width:25px;
height:auto;
}
div{
margin-left: 500px;
width: 200px;
height: 50px;
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/>
<div></div>
Jsfiddle: https://jsfiddle.net/3x7cgLdr/25/
if ($('#TargetDiv').is(':hover')) {
// alert('hello');
$("#image").addClass("red");
}else{
$("#image").removeClass("red");
}
Using this .is() function with :hover selector inside the
if(startMove){
}
Section simply does that without any hassle the is() function Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
.is() function documentation
var startMove;
$(document).mousemove(function(e) {
var difLeft = $('#image').offset().left - e.pageX;
var difTop = $('#image').offset().top - e.pageY;
if (difLeft < 10 && difLeft > -10 && difTop < 10 && difTop > -10) {
startMove = true;
$('html').removeClass('showCursor');
}
if (startMove) {
$("#image").css({
left: e.pageX,
top: e.pageY
});
if ($('#TargetDiv').is(':hover')) {
// alert('hello');
$("#image").addClass("red");
} else {
$("#image").removeClass("red");
}
} else {
$('html').addClass('showCursor');
}
});
$(document).mouseleave(function() {
startMove = false;
})
html {
cursor: none;
}
html.showCursor {
cursor: default;
}
#image {
position: absolute;
width: 25px;
height: auto;
}
#TargetDiv {
height: 100px;
width: 100px;
background: green;
margin: 100px auto;
}
.red {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png" />
<div id="TargetDiv">
</div>
I have added a class to set border red to the div when it hovers on the div with mouse and cursor image superimposed that is startMove="true".And removes when it is not hovered .I have commented the alert box;You can turn it on if you want
You already have a flag called startMove that is active whenever the cursor is dragged, use the mouseenter event on the target div as follows:
var startMove;
$(document).mousemove(function(e){
var difLeft = $('#image').offset().left - e.pageX;
var difTop = $('#image').offset().top - e.pageY;
if(difLeft < 10 && difLeft > -10 && difTop < 10 && difTop > -10 ){
startMove = true;
$('html').removeClass('showCursor');
}
if(startMove){
$("#image").css({left:e.pageX, top:e.pageY});
}
else{
$('html').addClass('showCursor');
}
});
$(document).mouseleave(function(){
startMove = false;
})
$("#drop").mouseenter(function(){
if(startMove)
alert("Success");
});
.
<img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/>
<div id="drop">
</div>
.
html {cursor: none;}
html.showCursor{cursor: default;}
#image{
position:absolute;
width:25px;
z-index: 100;
height:auto;
}
#drop{
width:100px;
height:100px;
background:green;
position: absolute;
left:200px;
top: 300px;
z-index:99
}
see a demo: https://jsfiddle.net/hycd913y/

Fade in another logo on scroll

I'm currently swapping a logo for smaller logo when the user scrolls down the page. At the moment it's a straight swap. However I'd like to add a nice animated fade in/out so the larger logo fades out, smaller logo fades in and vice-versa.
Here's a pen of my current attempt: http://codepen.io/abbasinho/pen/yyomrB
I've tried to adding fadeIn but with not joy.
JS:
$(function() {
var logo = $(".lrg-logo");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
logo.removeClass('lrg-logo').addClass("sml-logo").fadeIn( "slow");
} else {
logo.removeClass("sml-logo").addClass('lrg-logo').fadeIn( "slow");
}
});
});
CSS:
.wrapper {
height: 2000px;
position: relative;
background: green;
}
header {
position: fixed;
width: 100%;
height: 50px;
background: grey;
}
.lrg-logo {
width: 300px;
height: 50px;
text-align: center;
background: red;
}
.sml-logo {
width: 200px;
height: 20px;
text-align: center;
background: red;
}
2 things:
logo must first be hidden in order to fade it in.
fade should not happen on every scroll event, but just once when scrolltop > 500
$(function() {
var logo = $(".lrg-logo");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
if(!logo.hasClass("sml-logo")) {
logo.hide();
logo.removeClass('lrg-logo').addClass("sml-logo").fadeIn( "slow");
}
} else {
if(!logo.hasClass("lrg-logo")) {
logo.hide();
logo.removeClass("sml-logo").addClass('lrg-logo').fadeIn( "slow");
}
}
});
});
Use this
$(function() {
var logo = $(".lrg-logo");
var scrolling = false;
var small = false;
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500 && !scrolling && !small) {
scrolling = true;
logo.fadeOut(300);
window.setTimeout(function() {
logo.fadeIn( 300).removeClass('lrg-logo').addClass("sml-logo");
scrolling = false;
small = true;
}, 300);
} else if(!scrolling && small) {
scrolling = true;
logo.fadeOut( 300);
window.setTimeout(function() {
logo.fadeIn( 300).removeClass('sml-logo').addClass("lrg-logo");
scrolling = false;
small = false;
}, 300);
}
});
});
I have two flags. One to see if its currently animating or not. Another one to check if its small or large.
http://codepen.io/anon/pen/jEGNbN
the code is in the link above

Categories