28

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.

2
  • 1
    You should have a look at the jQuery Address plugin Commented Nov 21, 2011 at 13:51
  • 2
    @Sahil I assume he wants this so that he can use it on page load, for example to open a specific tab in a tab control. It is a handy technique to know about. Commented Nov 21, 2011 at 13:53

5 Answers 5

28

Try This

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

Its working for me

Sign up to request clarification or add additional context in comments.

Comments

24

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
}

4 Comments

See also the jQuery BBQ plugin, although that may be more complicated than the OP requires.
there is no such thing as $(window).haschange, and the question is about detecting URL change not haschange.
The $(window).haschange belongs to the mentioned plugin and the question is illustrated with an example by the OP
try instead: window.addEventListener("hashchange", myHashChangeHandler, false);
8

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
}

Comments

2

Try this:

if (window.location.hash) {
    // Fragment exists, do something with it
    var fragment = window.location.hash;
}

Just for reference, the part of a url specified by the # is called a 'fragment'

Comments

1

If you have a url of site.com/faq/#open, then you can do

var hash = window.location.hash

to get hash = 'open'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.