Should work for all anchor tags with #
hrefs.
<script>
$('a[href^=#]').click(function () { // Use all anchor tags with an href that starts with #
var href = $(this).attr('href'); // Get the href for the clicked anchor.
$(href).addClass( "animated swing" ); // The href is the same as the id.
$('html, body').animate({
scrollTop: $(href).offset().top
}, 500);
return false;
});
</script>
Taking into account @rorypicko's comment, a data attribute could be added to ensure only #
hrefs you require will use this functionality:
<a href="#ecomm" data-scroll-link>Text</a>
<script>
$('a[href^=#][data-scroll-link]').click(function () { // Use all anchor tags with an href that starts with # and the specified data attribute.
var href = $(this).attr('href'); // Get the href for the clicked anchor.
$(href).addClass( "animated swing" ); // The href is the same as the id.
$('html, body').animate({
scrollTop: $(href).offset().top
}, 500);
return false;
});
</script>