Help reduce the code:

$('#go-to-section-1').on('click', function() { $('html,body').animate({ scrollTop: $('#section-1').offset().top - 100 }, 300); }); $('#go-to-section-2').on('click', function() { $('html,body').animate({ scrollTop: $('#section-2').offset().top - 100 }, 300); }); $('#go-to-section-3').on('click', function() { $('html,body').animate({ scrollTop: $('#section-3').offset().top - 100 }, 300); }); 

I want to transfer this part to a variable, but I don’t know how:

 $('html,body').animate({ scrollTop: $('#section-3').offset().top - 100 }, 300); 

To be displayed on the similarity as:

 $('#go-to-section-1').on('click', function() { myTarget('#section-1'); }); 

    1 answer 1

     $("[id^='go-to-section-']").on('click', function() { function myTarget(index) { $('html,body').animate({ scrollTop: $('#section-' + index).offset().top - 100 }, 300); }; var parts = this.id.split("-"); myTarget(parts[parts.legth - 1]); }); 
    • It would be nice to add an explanation of what you did - Kromster