Cancel scroll to top action on click - javascript

I currently am using the following code to auto-scroll to the top on a callback from a swipe detect script. I want to add the ability to cancel the animation when the user clicks the screen during the animation.
$('body,html').animate({
scrollTop: 0
}, 300);
How would I accomplish this cancelation?

Use the stop method to stop the animation. Make sure to pass false for the jumpToEnd parameter so the user isn't automatically taken to the top of the screen.
$(function() {
//Substitute with whatever kicks off this scroll in your app.
$('button').on('click', function(evt) {
$('body,html').animate({
scrollTop: 0
}, 3000);
evt.stopPropagation();
});
$(window).on('click', function(evt) {
$('body,html').stop();
});
});
Live example - http://jsfiddle.net/FcLbH/2/
Edit - Removed the parameters to stop per #AvL's comment.

I am not quite sure about the click-detection, anyhow, this will stop the animation after 3 seconds:
$('body,html').animate({
scrollTop: 0
}, 6000);
setTimeout(function() { $('html,body').stop(); }, 3000);
For all the info on stop(): http://api.jquery.com/stop/

Maybe like this:
$('body,html').animate({
scrollTop: 0
}, 3000).click(function() {
$('body,html').stop();
});
example: http://jsfiddle.net/DJ8Re/1/

Related

How to cancel a javascript function if the user scrolls the page

Using this javascript to scroll to a div (#Content) after a 5s delay using setTimeout.
setTimeout(function () {
$('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 1000);
}, 5000);
How would I go about cancelling this action if the user scrolls manually before the 5s is elapsed. Reason being if the user has scrolled they'll be annoyed if the page then auto scrolls.
Tried putting it in window.load and checking for if ($(window).scrollTop() == 0) but of course that's always true at window.load, and isn't cancelled by the user scrolling manually.
Thanks!
you can use for example global variable and check if its set up by event scroll
var scrolled = false;
$(document).scroll(function(){scrolled = true;});
setTimeout(function () {
if (!scrolled){
$('html, body').animate({ scrollTop: $('#Content').offset().top - 0 },
1000); }
}
}, 5000);
You shall define your timeout into a variable to be able to cancel it with clearTimeout
See full documentation here : https://www.w3schools.com/jsref/met_win_cleartimeout.asp
Just add an event to check oyur scroll and cleart your timeout if scrolled
For example :
var myVar = setTimeout(function(){
$('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 1000);
}, 5000);
and to cancel your scroll :
$(document).scroll(function(){
clearTimeout(myVar)
}
You can clear the timeout as others have shown, or you can let it run but perform the scrollTop check inside before starting the scroll animation:
setTimeout(function () {
if ($(window).scrollTop() == 0) {
$('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 1000);
}
}, 5000);
You can run the logic for checking the scroll by adding an event hanlder for scroll and then removing the event handler once it is done checking as it needs to be run only once. Also, You can clear the setTimeout by using the clearTimeout in the eventHandler Code.
window.addEventListener('scroll', scrollEventHandler);
function scrollEventHandler(e){
clearTimeout(...setTimeoutid) // Pass in setTimeout Id.
}
setTimeout(function () {
$('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 1000);
window.removeEventListener('scroll', scrollEventHandler);
}, 5000);

Gradually scroll on mousedown until mouseup

How can I make the viewport scroll down gradually while the mouse button is pressed down over a position: fixed element?
Here you can accomplish this with jQuery.animate() in combination with setTimeout() and clearTimeout():
$('.button').on('mousedown', function() {
console.log('Start Animate');
(function smoothSrcroll() {
console.log(Math.max($('html').scrollTop(), $('body').scrollTop()));
$('html, body').stop().animate({
scrollTop: Math.max($('html').scrollTop(), $('body').scrollTop()) + 100
}, 1000, 'linear', function() {
window.timeout = setTimeout(smoothSrcroll(), 0);
});
})();
}).on('mouseup', function() {
console.log('Stop Animate');
$('html, body').stop();
clearTimeout(window.timeout);
});
CodePen Demo
I'm targeting $('html, body') so that it will work in both Firefox and Chrome. This gets a little tricky because the animate() actually runs twice because of the two selectors. To solve this I've used jQuery.stop(). Since Firefox can use the $('html').scrollTop() and Chrome uses the $('body').scrollTop(), I calculated the increment using Math.max(). The function is self-executing upon completion and uses clearTimeout() and jQuery.stop() when the mouse is released.

Click few times on button makes the page is blocked

When You click on button, page should scroll down, to div with id="myTarget".
here is my HTML:
<button class="go"> GO </button>
<div id="myTarget">
<p>
la lalal lalala lalala
</p>
</div>
and jquery:
$(function() {
$(".go").on('click', function(event) {
event.stopPropagation();
$('html, body').animate({
scrollTop: $("#myTarget").offset().top }, 3000);
});
});
My problem is that when you click a few times on button, page scroll down. After that you can't scroll up. Is any way to stop click event while page moving?
JsFiddle
And if you stop the animation when user mousewheel?
$(function() {
$(".go").on('click', function(event) {
event.stopPropagation();
$('html, body').animate({
scrollTop: $("#myTarget").offset().top }, 3000);
});
});
var page = $("html, body");
page.on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function(){
page.stop();
});
Demo
What about disabling the button while it is running and enabling it again once animation is done?
$(function() {
$(".go").on('click', function(event) {
var $but = jQuery(this);
event.stopPropagation();
$but.attr("disabled", true);
$('html, body').animate({
scrollTop: $("#myTarget").offset().top }, 3000, "linear", function(){
$but.removeAttr("disabled");
});
});
});
I assume you mean that if you rapidly click the button a couple of times it'll scroll down and not let you scroll back up, and not that it doesn't work when you "Click Button, Scroll Down, wait, Scroll Up".
If it's the first case, you can fix it like this.
$(function() { $(".go").on('click', function(event) {
event.stopPropagation();
$(".go").attr("disabled", true).delay(3000).attr("disabled", false); $('html, body').animate({
scrollTop: $("#myTarget").offset().top
},
3000);
});
});
This means that when you click on the button, it will be disabled for 3000 milliseconds (the time of your animation. This should stop a user from being able to click on it and trigger the animation more than once while it's animating.
The issue is that your animation is getting appended onto the previous animation for the html and body tags. Thus, you have to wait for all of the animations that have been started to die before you can scroll back up.
Things that you can do about this problem
Make the duration of the animation smaller
Call stop() on the elements you are animating before creating the new animation
Call stop() if the window is scrolled. This solution could be problematic if you ever have the body tag doing other animations. The first two solutions should be enough, anyway.
The first should be self explanatory and the second is very easy:
$(".go").on('click', function(event) {
event.stopPropagation();
$('body').stop().animate({
scrollTop: $("#myTarget").offset().top }, 500);
});
You also only need to animate the body element (not the html element).
JSFiddle Example
Use a scrolling state, like so :
$(function() {
//global var
isScrolling = false;
$(".go").on('click', function(event) {
event.stopPropagation();
if(!isScrolling) {
isScrolling = true;
$('html, body').animate({
scrollTop: $("#myTarget").offset().top }, 3000,
//Only when it's completed (callback)
function() {
isScrolling = false;
}
);
}
});
});
Your problem is that it keeps trying to scroll down even though you are already down.

Wait until a javascript function has finished before carrying out more

i have expandable headings that when clicked, show content.
I use a scrollTo method to scroll to the current clicked div to make sure its always in the screen view without the user scrolling.
However, where i currently use fadeIn / Out it looks messy as items are being faded in / out at the same time the page scrolling.
Is there a way i can only fade in / out the content when the scrollTo Has finished? e.g.:
Currently:
$(document).on('click','.headingHelp',function(){
$('html,body').animate({ scrollTop: $(this).offset().top }, 'slow');
$('.infoHelp').fadeOut();
$('.headingHelp_sel').attr('class', 'headingHelp');
$(this).next('.infoHelp').fadeIn();
$(this).attr('class', 'headingHelp_sel');
});
However what i want:
function scrollToDiv() {
$('html,body').animate({ scrollTop: $(this).offset().top }, 'slow');
}
$(document).on('click','.headingHelp',function(){
scrollToDiv() {
// ONLY DO THIS ONCE FINISHED SCROLLING
$('.infoHelp').fadeOut();
$('.headingHelp_sel').attr('class', 'headingHelp');
$(this).next('.infoHelp').fadeIn();
$(this).attr('class', 'headingHelp_sel');
}
});
You can use a callback:
$('html,body').animate({scrollTop: $(this).offset().top},'slow',function(){
//all the code you want to execute later goes here
});
If I recall correctly, you can make use of animate's promise:
function scrollToDiv() {
return $('html,body')
.animate({ scrollTop: $(this).offset().top }, 'slow').promise();
}
Use it like this:
scrollToDiv().done(function(){
$('.infoHelp').fadeOut();
$('.headingHelp_sel').attr('class', 'headingHelp');
$(this).next('.infoHelp').fadeIn();
$(this).attr('class', 'headingHelp_sel');
});

jQuery mmenu: Scroll after menu close

in an project I do use mmenu first time. It works as expected but there is one thing I would love to have working, but it still isn't :/
Here's the URL: http://1pager.gut-entwickelt.de/
What I would love to see: After selecting an menu-point, it shouldn't scroll within milliseconds. It should wait till the menu is closed, then start scrolling.
Thatfor I added this script-part:
Me.mobileMenu.mmenu({
zposition: "front",
onClick: {
preventDefault: true,
setSelected : false
}
});
Me.mobileMenu
.find('a')
.on(
'click',
function() {
var href = $(this).attr('href');
if (Me.mobileMenu.hasClass('mm-opened')) {
Me.mobileMenu
.off('closed.mm')
.one(
'closed.mm',
function() {
setTimeout(
function(){
$('html, body').animate({
scrollTop: $(href).offset().top
});
},
1000
);
return false;
}
);
} else {
setTimeout(
function(){
$('html, body').animate({
scrollTop: $(href).offset().top
});
},
1000
);
}
return false;
}
);
This seems to work here: http://mmenu.frebsite.nl/examples/responsive/index.html
But on that page it don't... any ideas?
Regards,
Oliver Lippert
The "closed" event is triggered when the menu finished closing, so you shouldn't need an extra timeout.
Have a look at this example, it's a bit more straightforward:
http://mmenu.frebsite.nl/mmenu/demo/onepage.html
Extended to Fred's reply I had another JS-code for doing the scroll. After disabling it, now the menu closes first, and the Scroll starts later.

Categories