user3767554 user3767554 - 4 months ago 7
jQuery Question

How to turn these 3 scripts into 1?

I have a script that does similar things for different id's and i'm pretty much certain this can be done in 1 script rather than 3, any suggestions are welcome.

$("#size-btn-one").click(function() {
$('html,body').animate({
scrollTop: $(".scroll-one").offset().top -100}, 2000);
});
});

$("#size-btn-two").click(function() {
$('html,body').animate({
scrollTop: $(".scroll-two").offset().top -100}, 2000);
});
});

$("#size-btn-three").click(function() {
$('html,body').animate({
scrollTop: $(".scroll-three").top -100}, 2000);
});
});

Answer

Combine the selector, you can make an and select by comma separation, like you did with html, body too. And you can extract the name from the element id by different ways, e.g with a simple replace.

$("#size-btn-one, #size-btn-two, #size-btn-three").click(function() {
    // getting only the last part of the elements id
    var id = $(this).attr("id").replace("size-btn-", "");

    $("html, body").animate({
        // append the 'id' to the selector class
        scrollTop: $(".scroll-" + id).offset().top -100}, 2000);
    });
});
Comments