Getting URL hash location and using it in jQuery

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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

Answers

https://developer.mozilla.org/En/DOM/Window.location https://developer.mozilla.org/En/DOM/Window.location

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

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

http://docs.jquery.com/Selectors/id http://docs.jquery.com/Selectors/id

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/substring https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/substring

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.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/1822598/getting-url-hash-location-and-using-it-in-jquery

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils