How can I trigger on URL change in jQuery?
How can I trigger a function when the URL changes? I try something like:
$(windows.location).change(function(){
//execute code
});
So my URL is something like http://www.mysite.com/index.html#/page/1
. How can I execute jQuery or JavaScript code when the URL becomes something like http://www.mysite.com/index.html#/page/2
?
That would be a hashchange
event, so I’d suggest:
$(window).on('hashchange', function(e){
// do something...
});
References:
on()
.
Try the hashchange
event, which is built exactly for this – http://benalman.com/projects/jquery-hashchange-plugin/
var current_href = location.href;
setInterval(function(){
if(current_href !== location.href){
// if changed Do ...
current_href = location.href;
}else{
// Do ...
}
},500);
This worked for me ^^
$(window).on(‘hashchange’) // not firing
You could also try using http://www.asual.com/jquery/address/
$(function(){
$.address.strict(false);
$.address.internalChange(function(e) {
// do something here
});
});
To Detect URL change only for pop use
window.onpopstate = function (event) {
//enter code here
}
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .