BeginnerP BeginnerP - 2 months ago 17
HTML Question

Splitting URL using JQuery

I want to split the URL using JQuery and get a certain value, if that value is set I would display a certain 'div' corresponding with that value. Example:

http://www.example.com/index.php#div1


I want to split the URL from the fragment identifier '#' and get the value coming after it 'div1'.

I then want to check using javascript/jquery if the value after the '#' is 'div1', I would display 'div1'.

var url = http://www.example.com/index.php#div1,
hash = url.split('#')[1];

if(hash == 'div1'){
$('.div1').show();
//if the hash is equal to 'div1' show the div with the class 'div1'
}

Answer

No need to do a split, just use location.hash with an id

For example, given the URL http://yoursite.com/page#div1, the location.hash would return #div1. You can use this to select the proper element.

ID Method:

// JS
$(window.location.hash).show();

<!-- HTML -->
<div id="div1">Hidden</div>

Class method:

Alternatively, if you must use a class, you will need to remove the # from the location.hash

// JS
// The substr method removes the `#` from the beginning.
// You can just as easily use `replace`
var hash = window.location.hash.substr(1);

$('.' + hash).show();

<!-- HTML -->
<div class="div1">Hidden</div>
Comments