views:

495

answers:

1

Heya guys.

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.

Any help would be massively appreciated!

Cheers

+6  A: 

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://site.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.

CMS