I have a static menu on the top of browser and when someone clicks on 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
});
});
You don't need to split the href
attribute, since it already includes the #
(which you check for 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;
});
});
Also, to make editing easier, you could change the offset from 100
to $('menu_element').height()
. If you ever change the menu, it will work without also having to edit the JS.
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