Search code examples
jquerywindow.locationfragment-identifier

Execute Code When The URL Has Hash OR HASH Changes After Load?


Any assistance would be greatly appreciated!

Execute code when a hash exists on load:

if(location.hash) { //code; }

Execute code when the hash changes:

$(window).hashchange(function(){//code;});

How do I combine these 2 checks?
This doesn't work:

if(location.hash || $(window).hashchange(function() { //code; });

Solution

  • Define a function for theCode, Pass its reference to hashchange event and on page load check if hash exists execute it directly

    function theCode() { //code; }
    
    if(location.hash){
        theCode();
    }
    
    $(window).hashchange(theCode);