Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to an element when a link is clicked [duplicate]

So I have the following website: http://www.gameplay-universe.uphero.com/

You can see the "Skip to Content" link. I want when it's clicked the page to scroll to div#content. I am using the latest version of jQuery. How can I achieve this?

like image 288
PowerUser Avatar asked Mar 21 '14 20:03

PowerUser


1 Answers

OK here's the solution I've found:

$(document).ready(function() {

// Click event for any anchor tag that's href starts with #
$('a[href^="#"]').click(function(event) {

    // The id of the section we want to go to.
    var id = $(this).attr("href");

    // An offset to push the content down from the top.
    var offset = 60;

    // Our scroll target : the top position of the
    // section that has the id referenced by our href.
    var target = $(id).offset().top - offset;

    // The magic...smooth scrollin' goodness.
    $('html, body').animate({scrollTop:target}, 500);

    //prevent the page from jumping down to our section.
    event.preventDefault();
});
});

That worked for me.

like image 145
PowerUser Avatar answered Oct 14 '22 00:10

PowerUser