Supapinzi Supapinzi - 1 month ago 6
jQuery Question

simplify jquery Sticky menu scroll to function

I am having a horizontal navigation on my one page website, which is becoming a sticky nav at a certain waypoint. Now I created a working scroll to navigation that looks like this

$(document).ready(function () {
$("#button0").click(function() {
$('html, body').animate({
scrollTop: $("#ziel_top").offset().top
}, 2000);
});
$("#button1").click(function() {
$('html, body').animate({
scrollTop: $("#ziel_1").offset().top-100
}, 2000);
});
$("#button2").click(function() {
$('html, body').animate({
scrollTop: $("#ziel_2").offset().top-100
}, 2000);
});
$("#button3").click(function() {
$('html, body').animate({
scrollTop: $("#ziel_3").offset().top-100
}, 2000);
});
$("#button4").click(function() {
$('html, body').animate({
scrollTop: $("#ziel_4").offset().top-100
}, 2000);
});
});


Now my question to you, would there be a method to simplify this function? Any ideas appreciated

Answer

assuming that all the #buttons are actually buttons:

$(document).ready(function () {
    $("a[id^=button]").click(function() {
        var id=$(this).attr('id');
        id=id.substr(id.length-1);
        if(id==0){
            $('html, body').animate({
                scrollTop: $("#ziel_top").offset().top
            }, 2000);
        }
        else{
            $('html, body').animate({
                scrollTop: $("#ziel_"+id).offset().top
            }, 2000);
        }
    });
});