Animation of transition to anchor links


By default, when you click on the anchor link, which looks like <a href=”#about”>About Us</a>, there is a sharp transition to the desired element on the site. If the transition occurs within one page, this effect looks ugly.
Better for such links, you can add an animation of a smooth transition (scroll) to the desired element.
You can do this with jQuery.

The small code below will help to make the site a little more presentable and beautiful.
The example shows an event when a user clicks a link in a menu with the class “menu”. Also, this code can be applied in general to all links on the site, since there is a check, anchor link or not.

$(document).ready(function(){
	$('.menu a').click(function(e){
    	if($(this).attr('href').indexOf('#') != -1){ // We check that the link is also an anchor link.
			e.preventDefault(); // Cancel the transition event.
            var href = $(this).attr('href').replace('#', ''); // We get from the anchor link the desired ID of the element to which the transition will occur.
			
			if($('#'+href).length > 0){ // Check if the element we need exists on the page.
            	var tophref = $('body').find('#'+href).offset().top; // We get the coordinates of the element, relative to the beginning of the page.
            	$('html, body').animate({scrollTop: tophref}, 800); // Create an animation of the scroll to the desired element.
			}
		}
    });
});



Connect

If you have any questions, want to get individual advice or you have an interesting offer, you can contact via the feedback form.

Or write to the email info@bobreod.ru





By submitting the form, you agree to our privacy policy