Reputation: 1
I have a couple of links anchored to hidden divs. These divs are hidden by setting the opacity to zero and I used jQuery to show these divs once I click on their respective anchor.
What I want to know is is it possible to open these divs using jQuery by just putting the anchors in the url? For example:
<a href="#div1">Link1</a>
<a href="#div2">Link2</a>
<a href="#div3">Link3</a>
<div id="div1">Lorem Ipsum</div>
<div id="div2">Vestibulum in sollicitudin</div>
<div id="div3">Mauris auctor</div>
The divs are initially hidden and only appears when the anchor is clicked. Now how do I open a certain div, say div2, onload by just adding the anchor at the end of the URL, like http://example.com#div2
Is it possible to do that?
Upvotes: 0
Views: 99
Reputation: 56501
You use also use toggle()
$('a').click(function(event){
var href = $(this).attr('href').replace('#','');
$(href).toggle();
event.preventDefault();
});
Updates: I think there is a bug in above code. Here is a working demo in JSFiddle
jQuery:
$('a').click(function (e) {
var href = $(this).attr('href');
$(href).toggle();
e.preventDefault();
});
Upvotes: 1
Reputation: 671
var links = document.getElementsByTagName('a');
function linkHandler(event){
event.preventDefault();
var div = document.getElementById(event.target.getAttribute('href').replace('#',''));
if(div.style.display == 'none'){
div.style.display = 'block';
} else {
div.style.display = 'none';
}
}
for(var i=0;i<links.length;i++){
links[i].addEventListener('click', linkHandler);
}
Upvotes: 0