Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect current url when any change happened

I am stripping url with "document.location.hash" and trying to check whats left behind from current url. I dont want to use any plugin and dont want to learn result from trigger events like click. Need to learn url change instantly and contemporary.

jQuery:

$(function() {
    $(document).location().change(function() {//this part is not working
        var anchor = document.location.hash;
        if( anchor === '#one' ) {
            alert('current url = #one');
        }else if ( anchor === '#two' ) {
            alert('current url = #two');
        }else if ( anchor === '#three' ) {
            alert('current url = #three');
        }
        console.log(anchor);
    });
});

html:

<a href="#one">one</a>
<a href="#two">two</a>
<a href="#three">three</a>

deep note: i have read these questions and cout find what i am looking for: How to detect URL change in JavaScript + How to change the current URL in javascript?

like image 252
Barlas Apaydin Avatar asked Nov 29 '25 10:11

Barlas Apaydin


2 Answers

Without using a plugin other than jQuery, you can handle the 'hashchange' event:

$(document).ready(function() {
    $(window).bind( 'hashchange', function(e) { 
    var anchor = document.location.hash;
            if( anchor === '#one' ) {
                alert('url = #one');
            }else if ( anchor === '#two' ) {
                alert('url = #two');
            }else if ( anchor === '#three' ) {
                alert('url = #three');
            }
            console.log(anchor);
    });
});

Caution: Not all browsers support the hashchange event.

Use with fallback: You should use Modernizr to detect if hashchangeEvent is supported and if that support check fails then fallback to Ben Alman's jQuery hashchange event plugin and use @Baylor Rae's solution in your else block.

like image 106
BumbleB2na Avatar answered Dec 02 '25 01:12

BumbleB2na


You might find Ben Alman's jQuery hashchange event plugin helpful.

$(function(){

  // Bind the event.
  $(window).hashchange( function(){
    // Alerts every time the hash changes!
    alert( location.hash );
  });

  // Trigger the event (useful on page load).
  $(window).hashchange();

});
like image 33
Baylor Rae' Avatar answered Dec 02 '25 00:12

Baylor Rae'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!