2


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

Saurabh
  • 85
  • 1
  • 9

4 Answers4

2

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:

  1. if(window.location.hash) { - only do this if there's a hash value at all.

  2. 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).

  3. 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.

Community
  • 1
  • 1
ASGM
  • 11,051
  • 1
  • 32
  • 53
0

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';
TechBytes
  • 563
  • 5
  • 16
0

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.

claustrofob
  • 5,448
  • 2
  • 19
  • 22
0

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');
 });
Sunil B N
  • 4,159
  • 1
  • 31
  • 52