I am making an FAQ page and have buttons across the top to jump to a category (it jumps to the p
tag that I use as the category label, ex. <p id="general">
for my general category).
Instead of just jumping right to the category, I want to add a scroll effect. I want something like http://www.dynamicdrive.com/dynamicindex3/scrolltop.htm that scrolls to the desired part of my page. That link is a script that goes to the top of the page with a nice scrolling effect. I need something similar that will scroll to where I link to. For example, if I want to go to a misc. category, I want to just be able to have <a href="#misc">Miscellaneous</a>
and have it scroll to that section of the page.
Use element. scroll() to Scroll to Bottom of Div in JavaScript. You can use element. scroll() to scroll to the bottom of an element.
To auto scroll a page from top to bottom we can use scrollTop() and height() method in jquery. In this method pass the document's height in scrollTop method to scroll.
click(function(event) { event. preventDefault(); $. scrollTo($('#myDiv'), 1000); });
If you want to scroll the current document to a particular place, the value of HREF should be the name of the anchor to which to scroll, preceded by the # sign. If you want to open another document at an anchor, give the URL for the document, followed by #, followed by the name of the anchor.
It is often required to move both body and html objects together.
$('html,body').animate({
scrollTop: $("#divToBeScrolledTo").offset().top
});
ShiftyThomas is right:
$("#divToBeScrolledTo").offset().top + 10 // +10 (pixels) reduces the margin.
So to increase the margin use:
$("#divToBeScrolledTo").offset().top - 10 // -10 (pixels) would increase the margin between the top of your window and your element.
$(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;
}
}
});
});
Check this link: http://css-tricks.com/snippets/jquery/smooth-scrolling/ for a demo, I've used it before and it works quite nicely.
Something like this would let you take over the click of each internal link and scroll to the position of the corresponding bookmark:
$(function(){
$('a[href^=#]').click(function(e){
var name = $(this).attr('href').substr(1);
var pos = $('a[name='+name+']').offset();
$('body').animate({ scrollTop: pos.top });
e.preventDefault();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With