Reputation: 115
I am trying to use anchor tag from URL in a javascript to show/hide a particular div in an html page. Here is an example for the same.
<div style="display:none;" id="test_one">Display this box when one</div>
<div style="display:none;" id="test_two">Display this box when two</div>
Now, what I want is, when the URL is http://www.example.com/this_page.html#test_one, I want to display first div (with id test_one). Similarly when the URL is http://www.example.com/this_page.html#test_two, I want to display second div (with id test_two).
Can any one please provide me any pointers on this?
Thanks in Advace
Upvotes: 2
Views: 1350
Reputation: 4225
Get URL from the page and hide that particular div only using JavaScript
CSS:
.hidden { display: none; }
HTML
<div id="test_one" class="hidden"><!-- div content --></div>
<div id="test_two" class="hidden"><!-- div content --></div>
and in jQuery
var pathArray = window.location.pathname.split( '#' );
var div_name = pathArray[1];
$(function () {
if(div_name=="test_one")
$('#test_one').removeClass('hidden');
else
$('#test_two').removeClass('hidden');
});
Upvotes: 0
Reputation: 11381
This should work for any hash/id pairs:
if(window.location.hash) {
var hash = window.location.hash.substring(1);
document.getElementById(hash).style.display = "inline";
}
Breaking it down:
if(window.location.hash) {
- only do this if there's a hash value at all.
var hash = window.location.hash.substring(1);
- put the hash value in a variable, removing the #
at the beginning (based on @Mark's answer to this question).
document.getElementById(hash).style.display = "inline";
- set the element on the page whose id
is the same as the hash to a visible display
value.
Upvotes: 2
Reputation: 4984
Take a look also at :target
pseudo selector:
div:target {
display: block;
}
Although it is not widely supported by browsers you can implement it as a first step of progressive enhancement.
Upvotes: 0
Reputation: 555
Try in the JS:
if(document.URL=' http://www.example.com/this_page.html#test_one')
document.getElementById('test_one').display='inline';
elseif(document.URL=' http://www.example.com/this_page.html#test_two')
document.getElementById('test_two').display='inline';
Upvotes: 0