HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Animated scrolling when intra-page links are clicked

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scrollingareanimatedlinkspagewhenclickedintra

Problem

I have the following code to get the ID of a and go to their respective div ``:

$('a[href=#certificados]').click(function(e){
    e.preventDefault();
    $("html, body").animate({ scrollTop: $('#certificados').offset().top }, 1000);
});

$('a[href=#team]').click(function(e){
    e.preventDefault();
    $("html, body").animate({ scrollTop: $('#team').offset().top }, 1000);
});

$('a[href=#house]').click(function(e){
    e.preventDefault();
    $("html, body").animate({ scrollTop: $('#house').offset().top }, 1000);
});

$('a[href=#contact]').click(function(e){
    e.preventDefault();
    $("html, body").animate({ scrollTop: $('#contact').offset().top }, 1000);
});


How could I optimize the code?

Solution

Get the "respective" div in a more general way from the link's href attribute:

$('a[href=#certificados], a[href=#team], a[href=#house], a[href=#contact]').click(function(e){
    e.preventDefault();
    $("html, body").animate({ scrollTop: $(this.hash).offset().top }, 1000);
    // this.hash would be equivalent to $(this).attr("href") in your case
});


Probably you also can use a much better selector now - maybe selecting those links by a common class.

Code Snippets

$('a[href=#certificados], a[href=#team], a[href=#house], a[href=#contact]').click(function(e){
    e.preventDefault();
    $("html, body").animate({ scrollTop: $(this.hash).offset().top }, 1000);
    // this.hash would be equivalent to $(this).attr("href") in your case
});

Context

StackExchange Code Review Q#39216, answer score: 11

Revisions (0)

No revisions yet.