Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect URL changes with jQuery

How can jQuery detect changes to a url?

For example: If a user goes to a page site.com/faq/ nothing shows, but if he goes to site.com/faq/#open jquery detects it and does something.

like image 303
skywind Avatar asked Nov 21 '11 13:11

skywind


3 Answers

Try This

$(window).on('hashchange', function(e){
 // Your Code goes here
});

Its working for me

like image 110
user3354817 Avatar answered Nov 20 '22 21:11

user3354817


You can use the hashchange event.

function hashchanged(){
  var hash = location.hash.replace( /^#/, '' );
 //your code
}

window.addEventListener("hashchange", hashchanged, false);

or integrate a jquery hashchange plugin

$(function(){

  // Bind the event.
  $(window).hashchange(hashchanged);

  // Trigger the event (useful on page load).
  hashchanged();

});

function hashchanged(){
 var hash = location.hash.replace( /^#/, '' );
 //your code
}
like image 36
unloco Avatar answered Nov 20 '22 21:11

unloco


Simply look at window.location.hash on page load:

$(document).ready(function() {
    if(window.location.hash === "open")
    {
        //Show something
    }
});

Or bind to the hashchange event of the window:

$(document).ready(function() {
    $(window).hashchange(hashchanged);
});

function hashchanged()
{
    //Show something
}
like image 8
James Hill Avatar answered Nov 20 '22 20:11

James Hill