Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to #id + 100 pixels

Tags:

html

jquery

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
    });
});
like image 756
Vlad S Avatar asked Jun 06 '12 18:06

Vlad S


1 Answers

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.

like image 146
Trojan Avatar answered Nov 13 '22 11:11

Trojan