jQuery: Anchor scrolling jumpy - javascript

I am using some code from www.css-tricks.com that can be used to animate local scrolling to a page anchor. Here is the code snippet:
$("class-name-here").on("click", function() {
var $target = $(this.hash);
$target = $target.length && $target
|| $('[name=' + this.hash.slice(1) +']');
if ($target.length) {
var targetOffset = $target.offset().top;
$('html,body')
.animate({scrollTop: targetOffset}, 1500, "easeOutQuint");
return false;
}
});
I have tried using a variety of times for the animation duration, but when I click the link, the page does scroll correctly, but after the scroll reaches the destination, the animation continues. In other words, it scrolls, but after the animation seems complete, if you try to scroll away manually, the page animates itself to that location again for about half a second.
Is there something wrong with the snippet / has anyone seen this before?

I found an example where we stop the scroll-event on different kind of events. I made an example for you without using jquery-ui. The scroll-timer is set to 2.5 sec so that you can stop it anytime before it reaches its target: JS-FIDDLE
function goTo(sectionID) {
var page = $("html, body");
page.on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function(){
page.stop();
});
page.animate({ scrollTop: $("#section" + sectionID).offset().top }, 2500, 'swing', function(){
page.off("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove");
});
return false;
};

Can you try this :
$('.your-class-name-here').click(function(event) {
var id = $(this).attr("href");
var offset = 10;
var target = $(id).offset().top - offset;
$('html, body').animate({scrollTop:target}, 1000);
event.preventDefault();
});
});

Related

Different scroll offset on mobile

I am using the following code to smooth scroll between links and it works perfectly.
I currently have an offset of 93px but wish to make this smaller, if not remove on small devices. I am wondering if its possible to change the offset value for smaller resolutions.
var jump=function(e)
{
if (e){
e.preventDefault();
var target = $(this).attr("href");
}else{
var target = location.hash;
}
$('html,body').animate(
{
scrollTop: $(target).offset().top-93
},2000,function()
{
location.hash = target;
});
}
$('html, body').hide();
$(document).ready(function()
{
$('a[href^=#]').bind("click", jump);
if (location.hash){
setTimeout(function(){
$('html, body').scrollTop(0).show();
jump();
}, 0);
}else{
$('html, body').show();
}
});
You can use JQuery $( window ).height() method to get the current window height and detect small devices. Based on this value you can display your offset differently.
More info here : https://api.jquery.com/height/

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.

preventing from animating further on some event

I've got this code here:
$(document).ready(function()
{
$("#nav_items > p:first-child").click(function()
{
$('html,body').animate(
{
scrollTop: $('#main_div').offset().top
}, 500);
});
$("#nav_items > p:last-child").click(function()
{
$('html,body').animate(
{
scrollTop: $('#about_us').offset().top
}, 800);
});
});
On element(p) click it scrolls the document to a #main_div or #about_us element. How can I stop it from keep on scrolling if I for example start scrolling with my mouse wheel?
You can listen to the mousewheel event and use the stop method:
$(window).on('mousewheel', function() {
$('body, html').stop();
});
Here is a method, combining the use of $(window).scroll() and $('body').on('mousewheel'), that will demonstrate how to do what you wish:
jsFiddle Demo
var scrollPause = 0;
menuItems.click(function(e){
var href = $(this).attr("href"),
offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
scrollPause = 1;
$('html, body').stop().animate({
scrollTop: offsetTop
}, 300, function(){
setTimeout(function(){
scrollPause = 0;
},5000);
});
e.preventDefault();
});
$('body').on({
'mousewheel': function(e) {
if (scrollPause == 0) return;
e.preventDefault();
e.stopPropagation();
}
})
Notes:
In the jsFiddle, the sp div is used to visually show status of the scrollPause variable
Upon clicking a top menu item, the scrollPause is set to 0 (disallow scroll) and a setTimeout is used to re-enable it after an 8-second pause. Therefore, immediately after the scroll-to-element, mouse wheel scroll will be disabled for 8 seconds.

jQuery Highlight Nav links on scroll not working

I'm extremely new to JavaScript so I apologize in advance. I'm trying to create a one page html document for a school project using a list of links for navigation that change when the anchor is scrolled to. I've tried various different methods found on Jfiddle and through stackoverflow. This is the method I am trying now: http://jsfiddle.net/m2zQE/
var topRange = 200, // measure from the top of the viewport to X pixels down
edgeMargin = 20, // margin above the top or margin from the end of the page
animationTime = 1200, // time in milliseconds
contentTop = [];
$(document).ready(function () {
// Stop animated scroll if the user does something
$('html,body').bind('scroll mousedown DOMMouseScroll mousewheel keyup', function (e) {
if (e.which > 0 || e.type == 'mousedown' || e.type == 'mousewheel') {
$('html,body').stop();
}
});
// Set up content an array of locations
$('#nav').find('a').each(function () {
contentTop.push($($(this).attr('href')).offset().top);
});
// Animate menu scroll to content
$('#nav').find('a').click(function () {
var sel = this,
newTop = Math.min(contentTop[$('#nav a').index($(this))], $(document).height() - $(window).height()); // get content top or top position if at the document bottom
$('html,body').stop().animate({
'scrollTop': newTop
}, animationTime, function () {
window.location.hash = $(sel).attr('href');
});
return false;
});
// adjust side menu
$(window).scroll(function () {
var winTop = $(window).scrollTop(),
bodyHt = $(document).height(),
vpHt = $(window).height() + edgeMargin; // viewport height + margin
$.each(contentTop, function (i, loc) {
if ((loc > winTop - edgeMargin && (loc < winTop + topRange || (winTop + vpHt) >= bodyHt))) {
$('#nav li')
.removeClass('selected')
.eq(i).addClass('selected');
}
});
});
});
I'm still not having any luck. I've already searched to see if I could debug the problem and have tried changing the order of the code as well as the order of calling jquery.
Here is a link to the site: https://googledrive.com/host/0BwvPQbnPrz_LMlZDeGlFY2Yydmc/index.html
I used html5boilerplate as a starting point.Thank you in advance.
Don't have much time to look into your code, but when I input the line
Math.min(contentTop[$('#nav a').index($(this))], $(document).height() - $(window).height())
into the console of developer tools, it return NaN.
So I guess the problem is you don't have your scrollTop correctly set.
I suggest you give each element an id and try:
$('html, body').animate({
scrollTop: $("#elementID").offset().top
}, 2000);
or if you insist not giving id,
$('html, body').animate({
scrollTop: $("#container-fulid:nth-child(2)").offset().top
}, 2000);
but notice that this is not working on all browser as the nth-child selector is a CSS3 selector.
Or, if you know how to correctly use other's work, you may try to use bootstrap 3.0, where there is already a function named scrollspy included, which do exactly the thing you are doing.
http://getbootstrap.com/javascript/#scrollspy

How to scroll page on multiple ID in js

Please check what i did yet http://jsfiddle.net/dUVmh/1/ .
About the animation i want to achieve is that:
When you first scroll down the page then window scroll to #green DIV. After that if you again scroll down window scroll to #yellow DIV & same at the time of scrollup (fom #yellow to #green).
About the issue:
You can see the animation it's stuck on #green DIV.
$(window).scroll(function(){
if($(this).scrollTop() > 0) {
$("html, body").animate({ scrollTop: $('#green').offset().top }, 1000);
}
else if($(this).scrollTop() > 1000) {
$("html, body").animate({ scrollTop: $('#yellow').offset().top }, 1000);
}
else{
$("html, body").animate({ scrollTop: $('#red').offset().top }, 1000);
}
});
I didn't have much experience in JS.
Thanks i advance :)
This was a fun problem to work on.
This solution places the divs into an array, and remembers the array index of the element that was last scrolled to. Once a scroll event is triggered it checks to see if the new scrollTop is above or below the current divs top offset and moves to the next or previous div in the array accordingly.
This solution allows you to have many divs. I tried to remove the flickering you get when you scroll to fast, but the only way to do that I believe would be to disable the scrollbars during animation.
http://jsfiddle.net/dUVmh/35/
$(function() {
var divs = [],
body = $('body, html'),
currentDiv = 0,
timeout;
$('div').each(function() {
divs.push($(this));
});
// we only need to capture the first scroll event triggered and then
// add another listener once we have done our animation
var scrollListen = function() {
$(window).one('scroll', function() {
doScroll($(this).scrollTop());
});
};
// Without the timeout, the scroll event would be triggered again too soon
var scrollEnd = function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
scrollListen();
}, 10);
};
// checks if the scroll direction was up and down and animates
// the body scrollTop to the next or previous div
var doScroll = function(scrollTop) {
var direction = scrollTop - divs[currentDiv].offset().top;
if (direction > 0 && currentDiv + 1 < divs.length) {
nextDiv = currentDiv + 1;
} else if (currentDiv - 1 > -1) {
nextDiv = currentDiv - 1;
}
if (currentDiv === nextDiv) {
scrollEnd();
}
body.animate({
scrollTop: divs[nextDiv].offset().top
}, 1000, function() {
currentDiv = nextDiv;
scrollEnd();
});
};
scrollListen();
});
Edit: Firefox scrollTop required to be changed on html and not body. Also fixed a problem with firefox calling scrollListen more than once at a time.
The problem is that the $(window).scroll(function()) gets called over and over again when scrolling through the ScrollTop animation with jQuery.
Here is a possible solution that checks if it is currently scrolling or not and only executes the ScrollTop animation once.
http://jsfiddle.net/dUVmh/29/
Side note: It might be a good idea to check which direction the user is scrolling (up or down) and depending on that scroll to the next div to the top or to the down.
You can check that be saving the last scrollTop position and comparing it with the current one.
UPDATE: Here's a solution that takes the scroll direction into account: http://jsfiddle.net/dUVmh/36/

Categories