Daniels Jirgensons Daniels Jirgensons - 1 month ago 21
Javascript Question

show/hide with same ids

I searched a lot on Stackoverflow, solution for my question, but no one of them helped me. I have a multiple show/hide (toggle) content, with same id's and I want to make, that the only one of them, what I need, opens, not all of them. There's my JSFiddle You can test it.

This is my JavaScript

$("#view").click(function(){
$('.hidden-content').slideToggle(500).toggleClass("active");
});

Answer

You cannot have duplicate id attributes within a single document. When you do only the first element with the given id is recognised; hence the issue you've seen.

Instead change the view elements to use a class, then use the this reference within the click event handler to traverse the DOM to find the related .hidden-content element and toggle it. Try this:

$(".view").click(function() {
  $(this).closest('.div').find('.hidden-content').slideToggle(500).toggleClass("active");
});
.div {
  width: 400px;
}
.content {
  padding: 10px;
}
.view {
  color: red;
  cursor: pointer;
}
.hidden-content {
  display: none;
}
.hidden-content .active {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">
  <div class="content">
    <div class="view">view/edit</div>
  </div>
  <div class="hidden-content">
    hidden content
  </div>
</div>

<div class="div">
  <div class="content">
    <div class="view">view/edit</div>
  </div>
  <div class="hidden-content">
    hidden content
  </div>
</div>

<div class="div">
  <div class="content">
    <div class="view">view/edit</div>
  </div>
  <div class="hidden-content">
    hidden content
  </div>
</div>

Comments