adamSiwiec adamSiwiec - 2 months ago 7
Javascript Question

Automating scrolling animations in jQuery

I am using jQuery to create a smooth animation from a link to a div.

$("#link").click(function() {
$('html, body').animate({
scrollTop: $("#portfolio").offset().top
}, 1000);
});


Since I am using this more than a couple times, I don't want to hard-code in the ids for each element. How could I automatically put the id in the stop that says "#link", and put the href ("#portfolio") of that id into the portfolio spot.

Answer

I would add a common class (instead of individual id's) to each element to which you want to have this click event attached. Then you could do something along the lines of:

$('.click-event-class').click(function() {
    var href = $(this).attr('href');
    $('html, body').animate({
          scrollTop: $(href).offset().top
     }, 1000);
});