Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle hidden divs by clicking on navigation?

Tags:

jquery

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()
})
like image 890
angela Avatar asked Apr 28 '14 12:04

angela


People also ask

How do I hide a div and then show on click?

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 .

How do I toggle div visibility?

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.

How do I toggle a div in CSS?

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.

How do I hide a div in HTML?

To hide an element, set the style display property to “none”. document. getElementById("element"). style.


2 Answers

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!

like image 154
Roko C. Buljan Avatar answered Oct 02 '22 18:10

Roko C. Buljan


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/

like image 42
Vassilis Blazos Avatar answered Oct 02 '22 17:10

Vassilis Blazos