Lieutenant Dan
Lieutenant Dan

Reputation: 8274

using jQuery to get current URL / path name > and detect if changes

I want to use jQuery to detect and get current URL / path, and if it changes from that, detect the change, and then .hide() an element with jQuery with typical jQuery .hide() method. Basically I want to show a element on a one page application only on the /#/home.php page any page after it will .hide()

So, get current URL.

If current URL is no longer as defined above,

.hide() div.


Or, alternatively: Display div content only if current URL is X.

Upvotes: 2

Views: 2044

Answers (3)

Deanveloper
Deanveloper

Reputation: 95

You can use the window.location.href along with Object.prototype.watch, although this function is currently only in Firefox Gecko (as of this answer) and this implementation by Eli Grey should be included: https://gist.github.com/eligrey/384583

Upvotes: 0

choz
choz

Reputation: 17858

There's no event in jQuery where it detects the url changing or whatsoever. But, I've come across this once and I used LocalStorage to solve my issue. Here's how my code mostly looks like.

E.g.

Page 1

$(document).ready(function(){
    // Check if browser supports LocalStorage
    if(typeof(Storage) !== 'undefined') {
        var origin = document.location.origin; // e.g. "http://stackoverflow.com"
        var pathname = document.location.pathname; // e.g. "/questions/36975059/using-jquery-to-get-current-url-path-name-and-detect-if-changes"

        localStorage.setItem('origin', origin);
        localStorage.setItem('pathname', pathname);
    }
});

Page 2 (Or wherever you want to detect if it changes)

$(document).ready(function(){
    // Check if browser supports LocalStorage
    if(typeof(Storage) !== 'undefined') {
        var origin = document.location.origin;
        var pathname = document.location.pathname;

        // Check if it changes here
        var storageOrigin = localStorage.getItem('origin');
        var storagePathname = localStorage.getItem('pathname');

        // Check if storageOrigin and storagePathname are not null or undefined.
        if (storageOrigin && storagePathname) {
            if (storageOrigin !== origin || storagePathname !== pathname) {
                // The previous origin and pathname are not the same. Do your things here.
            }
            else {
                // They're like the same.
            }
        }

        localStorage.setItem('origin', origin);
        localStorage.setItem('pathname', pathname);
    }
});

Hope it helps..

Upvotes: 1

Ash
Ash

Reputation: 2585

Are you looking to act upon the change of hash or new url? For hash handling:

$(window).on('hashchange', function(e){
 // handle the show/ hide of element here
})

Otherwise, you can use location object to find the URL values liek host, href etc.

$(location).attr('href');

$(location).attr('pathname');

Upvotes: 2

Related Questions