santa
santa

Reputation: 12512

show/hide divs with jQuery

I need to write a function, preferably in jQuery that allows to display a div with description of a corresponding item.

Here is what I have so far:

<img src="img1.png" id="img1">

<div id="div1" style="display:none">
description 1
</div>

<img src="img2.png" id="img2">

<div id="div2" style="display:none">
description 2
</div>

<img src="img3.png" id="img3">

<div id="div3" style="display:none">
description 3
</div>

Clicking on image1 should display div1. There can be only one div open at a time. But I think jQuery is the best route to take to solve this. Now sure how it is done...

Upvotes: 2

Views: 705

Answers (6)

Hogan
Hogan

Reputation: 70513

function showOnly(inDiv)
{
   $("#div1").hide();
   $("#div2").hide();
   $("#div3").hide();

   $(inDiv).show();
}

$(document).ready(function(){
  $("#img1").click(showOnly("#div1"));
  $("#img2").click(showOnly("#div2"));
  $("#img3").click(showOnly("#div3"));
});

There are ways to do this with a list, or using wild cards for the id number -- but I'm sure this will get you going in the right direction...

Upvotes: -1

Mathias E.
Mathias E.

Reputation: 471

$("img").bind("click", function(){
  var divid = $(this).attr(id);
  divid = divid.replace("img","div");
  $("#"+divid).toggle();
});

Upvotes: -1

Jamie Dixon
Jamie Dixon

Reputation: 53991

jQuery has a show() method that you can use to show a particular item.

If you want to be able to show/hide based on context you can use toggle().

Upvotes: 0

user463535
user463535

Reputation:

Bind a click event to the image that shows the div.

$("#img1").click( function() {
     $("#div1").show();
}

Upvotes: 0

Mike G
Mike G

Reputation: 4793

$('#img1').click(
       function() { 
          $('#div1').toggle(); 
 });

Upvotes: 1

Stefan Kendall
Stefan Kendall

Reputation: 67802

$(document).ready(function(){
  $('#img1').click(function(){
     $('#div1').show();//or use .toggle() to show/hide
  });
});

If you're always just toggling the next div after an image, give the images and divs classes, and handle it generically.

Ex: <img class="toggleImage"/><div class="toggledDiv"></div>

$('.toggleImage').click(function(){
  $(this).next('.toggledDiv').toggle();
});

And to ensure that only one div is open at a time, do this:

$('.toggleImage').click(function(){
  $(this).siblings('.toggledDiv').hide();
  $(this).next('.toggledDiv').show();
});

Upvotes: 4

Related Questions