Avoiding the following link without removing the "href" attribute

I need to postpone a slight redirect to a new page after clicking on certain links.

Now I am using the following jQuery:

$('.menu-element a').click(function(){ var src = $(this).attr('href'); $(this).removeAttr('href'); anim(src); }) 

And it works great. It starts a very short animation and then redirects to the page with a click.

But I would like to keep the href attribute of the link (i.e. in case someone double-clicks twice).

when I add $(this).attr('href', src); at the end of the code indicated above, he does not wait until the animation finishes only redirecting to a new page immediately after clicking the link.

How to save the href property and avoid redirecting the page to a new address?

+4
source share
2 answers

add return false to your function. This prevents the browser from following the href link, and then it's up to you to do this redirect in your javascript. for example by adding something to the end of your anim () function, which updates the location.

It also means that you do not need to remove href from the link.

 $('.menu-element a').click(function(){ var src = $(this).attr('href'); anim(src); return false; }) 
+6
source

You can use event.preventDefault () . return false will also work, but it also stops the event bubble (not a problem in most cases, you just need to know about it).

 $('.menu-element a').click(function(event){ anim($(this).attr('href')); event.preventDefault(); }) 
+4
source

Source: https://habr.com/ru/post/1347538/


All Articles