I have a JQuery
function which should allow smooth scrolling with JQuery
easing however it does not work and I can’t seem to find the error.
The code for the function is
$(function(){ $('a[href*=#]').click(function() { if (location.pathname.replace(/^//,”) == this.pathname.replace(/^//,”) && location.hostname == this.hostname) { 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}, {duration:1600,easing:'easeInBounce'}); return false; } } }); });
I made a JSFiddle with the function in to give an example. (I included the code for the JQuery
easing)
Here is a similar function in JSFiddle however, even though this one does work, it does not include the option to use easing. I would appreciate any help in fixing the problem
Edit
To expand on what I mean by it isn’t working; there is no animation when the links are clicked, it just instantly scrolls to that spot in the page.
Advertisement
Answer
You have some very weird things going on here.
On the following line you are using single double-quotes rather than two single quotes
if (location.pathname.replace(/^//,”) == this.pathname.replace(/^//,”) && location.hostname == this.hostname) {
On this line you are using characters that are not single quotes
$(‘html,body’).animate()
In the end we get this. jsFiddle
$(function(){ $('a[href*="#"]').click(function() { if (location.pathname.replace(/^//,'') == this.pathname.replace(/^//,'') && location.hostname == this.hostname) { 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}, {duration:1600,easing:'easeInBounce'}); return false; } } }); });
EDIT
To answer your questions in the comments of this answer, to get the “#” link working we change your $target =
line to this
$target = $target.length ? $target : $('html');
And to get the anchor to appear on the page we simple remove the return false;
from the function. After playing with the code I have reduced it to this:
$(function () { $('a[href*="#"]').click(function () { var $target = $(this.hash); $target = $target.length ? $target : $('html'); var targetOffset = $target.offset().top; $('html,body').animate({scrollTop: targetOffset}, {duration: 1600, easing: 'easeInBounce'}); }); });