Vlad S
Vlad S

Reputation: 113

Scroll to #id + 100 pixels

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
    });
});

Upvotes: 6

Views: 11814

Answers (1)

Trojan
Trojan

Reputation: 2254

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.

Upvotes: 8

Related Questions