The easiest way to to make the browser to scroll the page to a given anchor is to add *{scroll-behavior: smooth;} in your style. css file and in your HTML navigation use #NameOfTheSection .
The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0. When used to return the position: This method returns the vertical position of the scrollbar for the FIRST matched element.
Modern Browsers detect the hash in the url and then automatically open that part. So, if you want to scroll smoothly to that part instead, you first need to reset the scroll position to 0 and then add smooth scrolling. // direct browser to top right away if (window. location.
To set scrolltop position in jQuery, use the scrollTop() method. The scrollTop( ) method gets the scroll top offset of the first matched element. This method works for both visible and hidden elements.
You can do this using jQuery.offset()
and jQuery.animate()
.
Check out the jsFiddle Demonstration.
function scrollToAnchor(aid){
var aTag = $("a[name='"+ aid +"']");
$('html,body').animate({scrollTop: aTag.offset().top},'slow');
}
scrollToAnchor('id3');
Assuming that your href attribute is linking to a div with the tag id with the same name (as usual), you can use this code:
HTML
<a href="#goto" class="sliding-link">Link to div</a>
<div id="goto">I'm the div</div>
JAVASCRIPT - (Jquery)
$(".sliding-link").click(function(e) {
e.preventDefault();
var aid = $(this).attr("href");
$('html,body').animate({scrollTop: $(aid).offset().top},'slow');
});
function scroll_to_anchor(anchor_id){
var tag = $("#"+anchor_id);
$('html,body').animate({scrollTop: tag.offset().top},'slow');
}
This made my life so much easier. You basically put in your elements id tag and its scrolls to it without a lot of code
http://balupton.github.io/jquery-scrollto/
In Javascript
$('#scrollto1').ScrollTo();
In your html
<div id="scroollto1">
Here I am all the way down the page
You should also consider that the target has a padding and thus use position
instead of offset
. You can also account for a potential nav bar you don't want to be overlapping the target.
const $navbar = $('.navbar');
$('a[href^="#"]').on('click', function(e) {
e.preventDefault();
const scrollTop =
$($(this).attr('href')).position().top -
$navbar.outerHeight();
$('html, body').animate({ scrollTop });
})
My approach with jQuery to just make all of the embedded anchor links slide instead of jump instantly
It's really similar to the answer by Santi Nunez but it's more reliable.
<a href="#myid">Go to</a>
<div id="myid"></div>
// Slow scroll with anchors
(function($){
$(document).on('click', 'a[href^=#]', function(e){
e.preventDefault();
var id = $(this).attr('href');
$('html,body').animate({scrollTop: $(id).offset().top}, 500);
});
})(jQuery);
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