You do not need to split the href
attribute as it already includes #
(which you check in your selector).
$(function() { // Desired offset, in pixels var offset = 100; // Desired time to scroll, in milliseconds var scrollTime = 500; $('a[href^="#"]').click(function() { // Need both `html` and `body` for full browser support $("html, body").animate({ scrollTop: $( $(this).attr("href") ).offset().top + offset }, scrollTime); // Prevent the jump/flash return false; }); });
In addition, to simplify editing, you can change the offset from 100
to $('menu_element').height()
. If you ever change the menu, it will work without having to edit JS.
source share