Here is the solution that worked for me. This is a generic function which works for all of the a
tags referring to a named a
$("a[href^=#]").on('click', function(event) {
event.preventDefault();
var name = $(this).attr('href');
var target = $('a[name="' + name.substring(1) + '"]');
$('html,body').animate({ scrollTop: $(target).offset().top }, 'slow');
});
Note 1: Make sure that you use double quotes "
in your html. If you use single quotes, change the above part of the code to var target = $("a[name='" + name.substring(1) + "']");
Note 2: In some cases, especially when you use the sticky bar from the bootstrap, the named a
will hide beneath the navigation bar. In those cases (or any similar case), you can reduce the number of the pixels from your scroll to achieve the optimal location. For example: $('html,body').animate({ scrollTop: $(target).offset().top - 15 }, 'slow');
will take you to the target
with 15 pixels left on the top.