Search code examples
javascriptjquerywordpresshashchange

“hashchange” doesn't fire in Wordpress


Hi I am building this website: http://www.freiheitmedia.com/en/. It is build with the Themify Ultra theme.

My goal is to get rid of the #something part in the url when scrolling or clicking on a link.

I need to do it with JavaScript/jQuery because there is no theme based solution and the support staff can't help me.

I already tested and know that the following code replaces the url as I want:

history.replaceState("",document.title,window.location.pathname + window.location.search);

Now, the problem is that I seemingly can't get the "hashchange" event to fire. I am putting the following code in the footer and the alert statement is not reached in both cases:

<script>
    window.addEventListener("hashchange", function(e){
        alert("hiii");
    });
</script>

or

<script>
    window.addEventListener("hashchange", function(e){
        alert("hiii");
    }, false);
</script>

I suspect that the hashchange event might be prevented by the theme's settings but it's just a guess.

Do you guys have any idea why "hashchange" is not firing?


Solution

  • From your clarifying comment:

    when you visit the site, and scroll down, you will see that the url changes depending what section you are in. Specifically the #part changes. My goal was to prevent this behavior and have a clean url (without any #hashes) all the time.

    The best way to do that would be to find the plugin that's responding to scroll events by updating the hash (which is meant to be helpful, presumably; taking you back to that part of the page if you bookmark it) and turn it off. Fighting for control of the hash with a plugin on the page is a bad idea.

    Very much second-best to that:

    Since hashchange isn't firing, the plugin must be using history's replaceState or pushState or similar to set the hash, as that doesn't fire hashchange. You could replace those functions with your own version that strips the hash fragment:

    // I DON'T RECOMMEND THIS APPROACH
    (function() {
        function removeHash(url) {
            var u = String(url || "");
            var x = u.lastIndexOf("#");
            return x == -1 ? u : u.substring(0, x);
        }
        var originalReplaceState = history.replaceState;
        history.replaceState = function(state, title, url) {
            url = removeHash(url);
            return originalReplaceState.call(history, state, title, url);
        };
        var originalPushState = history.pushState;
        history.pushState = function(state, title, url) {
            url = removeHash(url);
            return originalPushState.call(history, state, title, url);
        };
    })();
    

    Again, though, really it's best to find whatever is responding to the scroll event by adding hash fragments and disable it.