B.Liu B.Liu - 6 months ago 8
Javascript Question

Show and Hide only one <div> using jQuery .hide/.show

The

.show
and
.hide
jQuery code works for every
<span>
with the class
.q_open
and
q_close
. I'm well aware that my because all my
<div>
tags have the class of
.answer
so they will show and hide both answers when I click on any
<span>
. Is there a way to reference only one
<div class=".answer">
when clicking on that
<span>
tag rather than giving each
<div>
a different
class
? Thanks!

The JavaScript code:

<script type="text/javascript">
$(function() {
$(".q_open").each(function() {
$(this).click(function() {
$(".answer").show();
});
})
$(".q_close").each(function() {
$(this).click(function() {
$(".answer").hide();
});
});
});
</script>


The HTML code:

<h2 class="question">
Q1: (the first question)
<span class="q_open"></span>
<span class="q_close"></span>
</h2>
<div class="answer" style="display: none;">
This should only open when clicked by the <span class="q_open"> for Q1.
</div>
<h2 class="question">
Q2: (the second question)
<span class="q_open"></span>
<span class="q_close"></span>
</h2>
<div class="answer" style="display: none;">
<p>
This should only open when clicked by the <span class="q_open"> for Q2.
</p>
</div>

Answer

replace class with id

 <script type="text/javascript">
 $(function() {
  $("#q1_open").click(function() {
      $("#answer1").show();
  });
 $("#q2_open").click(function() {
      $("#answer2").show();
  });
  $(".q_close").each(function() {
    $(this).click(function() {
      $("#answer1").hide();
      $("#answer2").hide();
    });
  });
});

Comments