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.

James Hill
  • 60,353
  • 20
  • 145
  • 161
skywind
  • 892
  • 6
  • 22
  • 44
  • 1
    You should have a look at the [jQuery Address plugin](http://www.asual.com/jquery/address/) – Richard Dalton Nov 21 '11 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. – Rory McCrossan Nov 21 '11 at 13:53

5 Answers5

27

Try This

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

Its working for me

user3354817
  • 309
  • 3
  • 4
22

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
}
unloco
  • 6,928
  • 2
  • 47
  • 58
  • 2
    See also the [jQuery BBQ plugin](http://benalman.com/projects/jquery-bbq-plugin/), although that may be more complicated than the OP requires. – Blazemonger Nov 21 '11 at 14:01
  • 1
    there is no such thing as $(window).haschange, and the question is about detecting URL change not haschange. – OviC Jun 23 '15 at 09:23
  • The `$(window).haschange` belongs to the mentioned plugin and the question is illustrated with an example by the OP – unloco Jun 23 '15 at 13:05
  • try instead: window.addEventListener("hashchange", myHashChangeHandler, false); – Gavin Sep 16 '15 at 17:58
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
}
James Hill
  • 60,353
  • 20
  • 145
  • 161
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'

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

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

var hash = window.location.hash

to get hash = 'open'

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
Utku Yıldırım
  • 2,277
  • 16
  • 20