Scroll to #id + 100 pixels

I have a static menu at the top of the browser, and when someone clicks on the links, the menu is above the text.

I did this, but scrollTop does not work:

 jQuery(document).ready(function () { $('a[href^="#"]').click(function() { var sHref = this.href.split("#"); $("#"+sHref[1]).scrollTop($("#"+sHref[1]).scrollTop() + 100); // <- does not work }); }); 
+4
source share
1 answer

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.

+6
source

Source: https://habr.com/ru/post/1416441/


All Articles