How do I toggle hidden divs by clicking on nav anchors?
Please see this fiddle http://jsfiddle.net/rabelais/4rfYB/1/
I have written it the very long way round by naming each id individually, however there must be a shorter way of writing this?
$('#link1').click(function() {
$('#1').show()
$('#2, #3').hide()
})
$('#link2').click(function() {
$('#2').show()
$('#1, #3').hide()
})
$('#link3').click(function() {
$('#3').show()
$('#2, #1').hide()
})
To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element. The onclick listener for the button will have a function that will change the display attribute of the <div> from the default value (which is block ) to none .
To toggle a div visibility in jQuery, use the toggle() method. It checks the div element for visibility i.e. the show() method if div is hidden. And hide() id the div element is visible. This eventually creates a toggle effect.
Instead of hiding it with the display CSS attribute, you can "move" it offscreen with something like position: absolute; left: -10000px; . +1, but it forces him to change the DOM, and use CSS3 selectors, which are probably a lot more users with them off then javascript off... but +1 anyway.
To hide an element, set the style display property to “none”. document. getElementById("element"). style.
http://jsfiddle.net/4rfYB/2/
$('nav a').click(function() {
$('.navLinks').hide(); // Hide all
$(this.getAttribute('href')).show(); // Show HREF/to/ID one
});
so you just need to get the href
of your anchor (i.e. #1
) and target the jQuery $()
element ID represented by that href value :)
If you want a oneliner: http://jsfiddle.net/4rfYB/5/
$('.navLinks').hide().filter(this.getAttribute('href')).show();
You can also use a less flexible way using .eq()
and .index()
http://jsfiddle.net/4rfYB/7/
$('.navLinks').hide().eq( $(this).index() ).show();
Note that numeric ID are only valid in HTML5!
without using nums 1,2,3
you could define it dynamically.
$('nav a').click(function() {
$('.navLinks').hide();
var index = $('nav a').index(this);
$('.navLinks').eq(index).show();
})
Please see this fiddle http://jsfiddle.net/rtGk6/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With