The code below allows you to scroll on both same and external pages. To make the link work you need to give it a class .scroll
. If you're linking to an anchor link on an external page, give the link a data-target="external"
as well.
$(document).ready(function() {
$('html, body').scrollTop(0);
var str = window.location.href;
if(str.indexOf('#') > -1) {
var anchor = str.substring(str.indexOf('#'));
setTimeout(function() {
$('html, body').animate({scrollTop: $(anchor).offset().top}, 'slow');
}, 100);
}
$('a.scroll').click(function(e) {
var trg = $(this).attr('data-target');
if(trg != 'external') {
e.preventDefault();
var href = $(this).attr('href');
$('html, body').animate({scrollTop: $(href).offset().top}, 'slow');
}
});
});
The link to an anchor on an external page will look like this:
<a href="inner.html#demo_2" class="scroll" data-target="external">DEMO 2</a>
Also, you can link to an anchor on the same page. In this case, you won't need to add any data-target
. I wrote the script the way that is supports both:
<a href="#demo_3" class="scroll">Go TO DEMO 3</a>