Robbie White
Robbie White

Reputation: 1588

Getting URL hash location, and using it in jQuery

I'd like to get the value after a hash in the URL of the current page and then be able to apply this in a new function... eg.

The URL could be

www.example.com/index.html#foo

And I would like to use this in conjunction with the following piece of code

$('ul#foo:first').show();

I'm kinda assuming/hoping there is some way of grabbing this, and turning it into a variable that I can then use in the second piece of code.

Upvotes: 145

Views: 271908

Answers (7)

A Friend
A Friend

Reputation: 1476

I found the marked answer wasn't sufficient for me. It states that getting the hash from the URL has huge security flaws but offers no real way of combatting it. There are ways out there of sanitizing the URL if you want to go that route, but if you're simply trying to show() a container, or apply some CSS/classes to the hash-matching ID container, then there's a much simpler way...

Introducing the :target selector.

The :target pseudo-class represents the unique element that has a matching id to the URL's fragment, meaning you can apply JS to it by simply doing something like:

$(':target').show();

Or in my case, just un-hiding the element I want with CSS only:

:target {
    display: block;
}

I know the OP's answer is almost exactly 13 years old, but this is a significantly easier and more secure way of achieving the same effect without dealing with getting the URL, splitting it up, sanitizing it - and hell, you can even avoid JS altogether with this method.

And yes, the :target selector is well-supported

Upvotes: 2

squarecandy
squarecandy

Reputation: 5107

I'm using this to address the security implications noted in @CMS's answer.

// example 1: www.example.com/index.html#foo

// load correct subpage from URL hash if it exists
$(window).on('load', function () {
    var hash = window.location.hash;
    if (hash) {
        hash = hash.replace('#',''); // strip the # at the beginning of the string
        hash = hash.replace(/([^a-z0-9]+)/gi, '-'); // strip all non-alphanumeric characters
        hash = '#' + hash; // hash now equals #foo with example 1

        // do stuff with hash
        $( 'ul' + hash + ':first' ).show();
        // etc...
    }
});

Upvotes: 3

j08691
j08691

Reputation: 207861

Since jQuery 1.9, the :target selector will match the URL hash. So you could do:

$(":target").show(); // or $("ul:target").show();

Which would select the element with the ID matching the hash and show it.

Upvotes: 5

eQ19
eQ19

Reputation: 10691

I would suggest better cek first if the current page has a hash. Otherwise it will be undefined.

$(window).on('load', function(){        
    if( location.hash && location.hash.length ) {
       var hash = decodeURIComponent(location.hash.substr(1));
       $('ul'+hash+':first').show();;
    }       
});

Upvotes: 2

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827178

Editor's note: the approach below has serious security implications and, depending upon the version of jQuery you are using, may expose your users to XSS attacks. For more detail, see the discussion of the possible attack in the comments on this answer or this explanation on Security Stack Exchange.

You can use the location.hash property to grab the hash of the current page:

var hash = window.location.hash;
$('ul'+hash+':first').show();

Note that this property already contains the # symbol at the beginning.

Actually you don't need the :first pseudo-selector since you are using the ID selector, is assumed that IDs are unique within the DOM.

In case you want to get the hash from an URL string, you can use the String.substring method:

var url = "http://example.com/file.htm#foo";
var hash = url.substring(url.indexOf('#')); // '#foo'

Advice: Be aware that the user can change the hash as he wants, injecting anything to your selector, you should check the hash before using it.

Upvotes: 298

Matas Vaitkevicius
Matas Vaitkevicius

Reputation: 61351

For those who are looking for pure javascript solution

 document.getElementById(location.hash.substring(1)).style.display = 'block'

Hope this saves you some time.

Upvotes: 6

Deepak Patil
Deepak Patil

Reputation: 3489

location.hash is not safe for IE , in case of IE ( including IE9 ) , if your page contains iframe , then after manual refresh inside iframe content get location.hash value is old( value for first page load ). while manual retrieved value is different than location.hash so always retrieve it through document.URL

var hash = document.URL.substr(document.URL.indexOf('#')+1) 

Upvotes: 37

Related Questions