Reputation: 48091
Is there a way to scroll down to an anchor link using jQuery?
Like:
$(document).ready(function(){
$("#gotomyanchor").click(function(){
$.scrollSmoothTo($("#myanchor"));
});
});
?
Upvotes: 65
Views: 162337
Reputation: 4245
Here is how I do it:
var hashTagActive = "";
$(".scroll").on("click touchstart" , function (event) {
if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
event.preventDefault();
//calculate destination place
var dest = 0;
if ($(this.hash).offset().top > $(document).height() - $(window).height()) {
dest = $(document).height() - $(window).height();
} else {
dest = $(this.hash).offset().top;
}
//go to destination
$('html,body').animate({
scrollTop: dest
}, 2000, 'swing');
hashTagActive = this.hash;
}
});
Then you just need to create your anchor like this:
<a class="scroll" href="#destination1">Destination 1</a>
A demo is also available here: http://jsfiddle.net/YtJcL/
Upvotes: 122
Reputation: 491
I would use the simple code snippet from CSS-Tricks.com:
$(function() {
$('a[href*=#]:not([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) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
Source: http://css-tricks.com/snippets/jquery/smooth-scrolling/
Upvotes: 49
Reputation: 27301
I wanted a version that worked for <a href="#my-id">
and <a href="/page#my-id">
<script>
$('a[href*=#]:not([href=#])').on('click', function (event) {
event.preventDefault();
var element = $(this.hash);
$('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
});
</script>
Upvotes: 3
Reputation: 1919
Best solution I have seen so far: jQuery: Smooth Scrolling Internal Anchor Links
HTML:
<a href="#comments" class="scroll">Scroll to comments</a>
Script:
jQuery(document).ready(function($) {
$(".scroll").click(function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});
});
Upvotes: 42
Reputation: 7597
I hate adding function-named classes to my code, so I put this together instead. If I were to stop using smooth scrolling, I'd feel behooved to go through my code, and delete all the class="scroll" stuff. Using this technique, I can comment out 5 lines of JS, and the entire site updates. :)
<a href="/about">Smooth</a><!-- will never trigger the function -->
<a href="#contact">Smooth</a><!-- but he will -->
...
...
<div id="contact">...</div>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
// Smooth scrolling to element IDs
$('a[href^=#]:not([href=#])').on('click', function () {
var element = $($(this).attr('href'));
$('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
return false;
});
</script>
Requirements:
1. <a>
elements must have an href attribute that begin with #
and be more than just #
2. An element on the page with a matching id
attribute
What it does:
1. The function uses the href value to create the anchorID
object
- In the example, it's $('#contact')
, /about
starts with /
2. HTML
, and BODY
are animated to the top offset of anchorID
- speed = 'normal' ('fast','slow', milliseconds, )
- easing = 'swing' ('linear',etc ... google easing)
3. return false
-- it prevents the browser from showing the hash in the URL
- the script works without it, but it's not as "smooth".
Upvotes: 0
Reputation: 1218
Try this one. It is a code from CSS tricks that I modified, it is pretty straight forward and does both horizontal and vertial scrolling. Needs JQuery. Here is a demo
$(function() {
$('a[href*=#]:not([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) {
$('html,body').animate({
scrollTop: target.offset().top-10, scrollLeft:target.offset().left-10
}, 1000);
return false;
}
}
});
});
Upvotes: 2
Reputation: 21
works
$('a[href*=#]').each(function () {
$(this).attr('href', $(this).attr('href').replace('#', '#_'));
$(this).on( "click", function() {
var hashname = $(this).attr('href').replace('#_', '');
if($(this).attr('href') == "#_") {
$('html, body').animate({ scrollTop: 0 }, 300);
}
else {
var target = $('a[name="' + hashname + '"], #' + hashname),
targetOffset = target.offset().top;
if(targetOffset >= 1) {
$('html, body').animate({ scrollTop: targetOffset-60 }, 300);
}
}
});
});
Upvotes: 1
Reputation: 282805
Using hanoo's script I created a jQuery function:
$.fn.scrollIntoView = function(duration, easing) {
var dest = 0;
if (this.offset().top > $(document).height() - $(window).height()) {
dest = $(document).height() - $(window).height();
} else {
dest = this.offset().top;
}
$('html,body').animate({
scrollTop: dest
}, duration, easing);
return this;
};
usage:
$('#myelement').scrollIntoView();
Defaults for duration and easing are 400ms and "swing".
Upvotes: 1
Reputation: 487
I used the plugin Smooth Scroll, at http://plugins.jquery.com/smooth-scroll/. With this plugin all you need to include is a link to jQuery and to the plugin code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/smoothscroll.js"></script>
(the links need to have the class smoothScroll
to work).
Another feature of Smooth Scroll is that the ancor name is not displayed in the URL!
Upvotes: 0
Reputation: 203
I used in my site this:
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 1200, 'swing', function () {
window.location.hash = target;
});
});
});
You could change the speed of the scrolling changing the "1200" i used by default, it works fairly well on most of the browsers.
after putting the code between the <head> </head>
tag of your page, you will need to create the internal link in your <body>
tag:
<a href="#home">Go to Home</a>
Hope it helps!
Ps: Dont forget to call:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
Upvotes: 0
Reputation: 1414
Here's the code I used to quickly bind jQuery scrollTo to all anchor links:
// Smooth scroll
$('a[href*=#]').click(function () {
var hash = $(this).attr('href');
hash = hash.slice(hash.indexOf('#') + 1);
$.scrollTo(hash == 'top' ? 0 : 'a[name='+hash+']', 500);
window.location.hash = '#' + hash;
return false;
});
Upvotes: 4
Reputation: 150739
jQuery.scrollTo will do everything you want and more!
You can pass it all kinds of different things:
Upvotes: 12