Joshua Soileau
Joshua Soileau

Reputation: 3015

Using Javascript, Prevent Scroll on Empty URL Hash Change

I want to detect hashchanges, and if the hash is empty, prevent it from scrolling to the top of the screen.

Here's what I have:

// Older version of jQuery, so can't use .on()
jQuery(window).bind("hashchange", function (e) {
    if (window.location.hash == "") e.preventdefault();
    else alert(window.location.hash);
});

Put that into your console, and you can see that it correctly detects hash changes and alerts if they are not just "#", but if you change it append "#" to your url, it still scrolls to the top.

How do I prevent the screen from going to the top of the page when you add an empty hash, "#", to your url?

Upvotes: 3

Views: 829

Answers (1)

Kyle B.
Kyle B.

Reputation: 5787

    $(function() {
        $('a').click(function(e) {
             var lnkHref = $(this).attr('href');
             if (lnkHref.substr(lnkHref.length - 1) == '#')
             {             
                 e.preventDefault();

                 // optional if you want to redirect still
                 var trimmedUrl = lnkHref.substr(0, lnkHref.length - 1);
                 document.location.href = trimmedUrl;
             }
        }); 
     })

Upvotes: 2

Related Questions