Use jQuery preventDefault (), but add the path to the url

I am working on a site where clicking on a specific link will move down the login panel. I use event.preventDefault() to stop the site redirecting, as well as an animation event, to move the panel down. When a click is clicked, the panel slides down and the URL remains unchanged.

What I want to do when I clicked the link is to animate the panel as usual, but for the href attribute of the link, which will be displayed in the URL. In this case, it will be something like this: http://domain_name/#login .

Here is the code I received right now:

 $("#login_link").click(function (e) { e.preventDefault(); $("#login").animate({ 'margin-top': 0 }, 600, 'linear'); window.location.hash = $(this).attr('href'); }); 

This code successfully adds '#login' to the URL as desired, but it skips the login bar animation. When you click on the link, the panel immediately appears. I would like to keep both the animation and the updated url behavior. Is it possible?

+8
javascript jquery preventdefault
source share
2 answers

use below code. just call the hash in the completed animation event.

 $("#login_link").click(function (e) { e.preventDefault(); $("#login").animate({ 'margin-top': 0 }, 600, 'linear', function(){ window.location.hash = $(this).attr('href'); }); }); 
+2
source share

I'm not sure, but you can look for this function

1> when someone clicks on the login, the URL changes to abc.com/#login and the login panel animation appears

or

2> When some body simply types abc.com/#login in the url, you expect the same behavior (animation of the login panel).

What you are currently doing will work only for case1 and will not work for case2. If you want the animation (or something else) to work both when clicked and when printed by URL. You need some kind of mechanism to detect hash changes.

There is a famous plugin http://benalman.com/projects/jquery-bbq-plugin/

Go and see this plugin and see how everything is done. If you find something difficult to understand, we are here!

+1
source share

All Articles