Do jQuery wait for href changes before reading href?
Provide the following markup:
<a href="#link01">1</a> <a href="#link02">2</a> and
$('a').click(function(){ var href = $(location).attr('href'), hrefLenght = href.length, hrefPos = href.indexOf("#"), hrefPage = href.slice(hrefPos+1); alert(hrefPage); }); Now, when you click the link, the following will happen: jQuery notifies the hrefPage that was there before , clicked the link, and not after , as expected. Therefore:
1) I am at http://www.example.com/#link01
2) I click the link
3, result) link01 reflected
3, expected) link02 reflected
Any ideas how to fix this?
EDIT: Why am I using location instead of href? Since I want the above code to work as well when the page loads with href without any clicks, and I don't think it is a good idea to write two code snippets for the same process?
You can use the hashchange event to track these changes:
$('a').bind('hashchange',function(){ var hval = location.hash.slice(1); // remove the leading # alert(hval); }); To start the hashchange download on the page, so it launches external hash links or when you view the back button (instead of clicking the link), add this:
$(document).ready(function() { $(window).trigger('hashchange'); }); Why not use the href link you clicked? it will have the value that href will have after changing it.
$('a').click(function(){ var href = this.href, hrefLength = href.length, hrefPos = href.indexOf("#"), hrefPage = href.slice(hrefPos+1); alert(hrefPage); // could also use: // alert(this.href.split("#")[1]); }); you need the url to change before javascript is run. One way to do this is to simply put
window.location = $(this).attr('href'); at the top of javascript code to make the window navigation action happen before your javascript
example: http://jsfiddle.net/btdqe/