jQuery - hashchange event
Asked Answered
U

12

92

I am using:

$(window).bind( 'hashchange', function(e) { });

to bind a function to the hash change event. This seems to work in IE8, Firefox and Chrome, but not in Safari and I assume not in earlier version of IE. For these browsers, I want to disable my JavaScript code that uses the hash and hashchange event.

Is there a way with jQuery that i can detect if the browser supports the hashchange event? Maybe something with jQuery.support...

Unbosom answered 22/6, 2010 at 5:20 Comment(1)
jQuery hashchange event - jQuery plugin works perfect, even in IE8. + it's very easy to use it :)Orcinol
H
71

You can detect if the browser supports the event by:

if ("onhashchange" in window) {
  //...
}

See also:

Halbert answered 22/6, 2010 at 5:22 Comment(2)
Thanks for that and for the quick response.Unbosom
Note that IE8 running in IE7 compatibility mode reports true for 'onhashchange' in window, even though the event isn't supported -from jQuery MobileMoir
H
51

An updated answer here as of 2017, should anyone need it, is that onhashchange is well supported in all major browsers. See caniuse for details. To use it with jQuery no plugin is needed:

$( window ).on( 'hashchange', function( e ) {
    console.log( 'hash changed' );
} );

Occasionally I come across legacy systems where hashbang URL's are still used and this is helpful. If you're building something new and using hash links I highly suggest you consider using the HTML5 pushState API instead.

Haplosis answered 10/10, 2017 at 14:41 Comment(1)
This works well, use window.location.hash to access the current hash.Step
L
19

There is a hashchange plug-in which wraps up the functionality and cross browser issues available here.

Liven answered 22/6, 2010 at 5:53 Comment(1)
Only required for < IE8Liven
D
18

A different approach to your problem...

There are 3 ways to bind the hashchange event to a method:

<script>
    window.onhashchange = doThisWhenTheHashChanges;
</script>

Or

<script>
    window.addEventListener("hashchange", doThisWhenTheHashChanges, false);
</script>

Or

<body onhashchange="doThisWhenTheHashChanges();">

These all work with IE 9, FF 5, Safari 5, and Chrome 12 on Win 7.

Disulfide answered 29/6, 2011 at 15:25 Comment(0)
E
8

try Mozilla official site: https://developer.mozilla.org/en/DOM/window.onhashchange

cite as follow:

if ("onhashchange" in window) {
    alert("The browser supports the hashchange event!");
}

function locationHashChanged() {
    if (location.hash === "#somecoolfeature") {
        somecoolfeature();
    }
}

window.onhashchange = locationHashChanged;
Endotoxin answered 7/9, 2011 at 3:0 Comment(0)
U
3

Note that in case of IE 7 and IE 9 if statment will give true for ("onhashchange" in windows) but the window.onhashchange will never fire, so its better to store hash and check it after every 100 millisecond whether its changed or not for all versions of IE.

    if (("onhashchange" in window) && !($.browser.msie)) { 
         window.onhashchange = function () { 
              alert(window.location.hash);             
         }            
         // Or $(window).bind( 'hashchange',function(e) {  
         //       alert(window.location.hash); 
         //   });              
    }
    else { 
        var prevHash = window.location.hash;
        window.setInterval(function () {
           if (window.location.hash != prevHash) {
              prevHash = window.location.hash;
              alert(window.location.hash);
           }
        }, 100);
    }
Urine answered 28/6, 2011 at 15:27 Comment(3)
Isn't this too much for the browser to handle? to poll for a hash change every 100ms?Already
your sample code made my IE8 alerting until i opened task manager and killed process :)Orcinol
that's because there's a typo, instead of "storedHash" use "prevHash" and it will work. He basically used a different variable name from how it's been declared.Allotment
D
3

I just ran into the same problem (lack of hashchange event in IE7). A workaround that suited for my purposes was to bind the click event of the hash-changing links.

<a class='hash-changer' href='#foo'>Foo</a>

<script type='text/javascript'>

if (("onhashchange" in window) && !($.browser.msie)) { 

    //modern browsers 
    $(window).bind('hashchange', function() {
        var hash = window.location.hash.replace(/^#/,'');
        //do whatever you need with the hash
    });

} else {

    //IE and browsers that don't support hashchange
    $('a.hash-changer').bind('click', function() {
        var hash = $(this).attr('href').replace(/^#/,'');
        //do whatever you need with the hash
    });

}

</script>
Doing answered 6/7, 2012 at 22:12 Comment(1)
you could use $('a[href^="#"]') to get links to hrefs beginning with a hash, avoiding the need for a class addLoveless
P
3

What about using a different way instead of the hash event and listen to popstate like.

window.addEventListener('popstate', function(event)
{
    if(window.location.hash) {
            var hash = window.location.hash;
            console.log(hash);
    }
});

This method works fine in most browsers i have tried so far.

Pharmacopoeia answered 2/9, 2015 at 8:37 Comment(1)
Popstate is even newer than hashchange. For instance, it's not supported in IE < 10.Infantryman
D
1

this tiny jQuery plugin is very simple to use: https://github.com/finnlabs/jquery.observehashchange/

Deil answered 8/8, 2012 at 6:50 Comment(0)
L
0

I think Chris Coyier has solution for that hashing problem, have a look at his screencast:

Best Practices with Dynamic Content

Lemus answered 22/6, 2010 at 5:24 Comment(0)
C
0

Use Modernizr for detection of feature capabilities. In general jQuery offers to detect browser features: http://api.jquery.com/jQuery.support/. However, hashchange is not on the list.

The wiki of Modernizr offers a list of libraries to add HTML5 capabilities to old browsers. The list for hashchange includes a pointer to the project HTML5 History API, which seems to offer the functionality you would need if you wanted to emulate the behavior in old browsers.

Chaoan answered 9/5, 2013 at 10:6 Comment(0)
B
0

Here is updated version of @johnny.rodgers

Hope helps someone.

// ie9 ve ie7 return true but never fire, lets remove ie less then 10
if(("onhashchange" in window) && navigator.userAgent.toLowerCase().indexOf('msie') == -1){ // event supported?
    window.onhashchange = function(){
        var url = window.location.hash.substring(1);
        alert(url);
    }
}
else{ // event not supported:
    var storedhash = window.location.hash;
    window.setInterval(function(){
        if(window.location.hash != storedhash){
            storedhash = window.location.hash;
            alert(url);
        }
    }, 100);
}
Bellarmine answered 15/4, 2015 at 12:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.