Event in a single div with equal classes. How to make?

1

Greetings. I created some div inside a foreach, all with the same class, inside this div has an element that I want, when clicked, show another div that is inside the created parent div. However, as expected, when I trigger such an event, all sub-divs of all created divs are displayed.

For example, here's a code that replicates what I'm doing:

HTML:

<div class='pai'> 
   <i class='elementoDisparo'>
   <div class="divQueAparece">
</div>

<div class='pai'>
    <i icon dropdown class='elementoDisparo'>
    <div class="divQueAparece">
</div>

 <div class='pai'>
    <i icon dropdown class='elementoDisparo'>
    <div class="divQueAparece">
</div>

JavaScript

window.addEventListener('load', function(){
  $(".divQueAparece").hide();
  $(".elementoDisparo").click(function(){
     $(".divQueAparece").toggle(300);
  });

});
    
asked by anonymous 25.04.2018 / 19:18

1 answer

1

You need to find only the div that is in the same%% of parent%. As you are doing, you are applying div to all with .toogle class. You can do it as below:

window.addEventListener('load', function(){
  $(".divQueAparece").hide();
  $(".elementoDisparo").click(function(){
     $(this)
     .closest(".pai")
     .find(".divQueAparece")
     .toggle(300);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass='pai'><iicondropdownclass='elementoDisparo'>clique-me1</i><divclass="divQueAparece">div filho 1</div>
</div>

<div class='pai'>
    <i icon dropdown class='elementoDisparo'>clique-me2</i>
    <div class="divQueAparece">div filho 2</div>
</div>

<div class='pai'>
    <i icon dropdown class='elementoDisparo'>clique-me3</i>
    <div class="divQueAparece">div filho 3</div>
</div>

If you want one to close after opening another , just add:

$(".divQueAparece:visible")
.not($this)
.toggle(300);

Example:

window.addEventListener('load', function(){
  $(".divQueAparece").hide();
  $(".elementoDisparo").click(function(){

     var $this = $(this).closest(".pai").find(".divQueAparece");

     $(this)
     .closest(".pai")
     .find(".divQueAparece")
     .toggle(300);

     $(".divQueAparece:visible")
     .not($this)
     .toggle(300);
     
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass='pai'><iicondropdownclass='elementoDisparo'>clique-me1</i><divclass="divQueAparece">div filho 1</div>
</div>

<div class='pai'>
    <i icon dropdown class='elementoDisparo'>clique-me2</i>
    <div class="divQueAparece">div filho 2</div>
</div>

<div class='pai'>
    <i icon dropdown class='elementoDisparo'>clique-me3</i>
    <div class="divQueAparece">div filho 3</div>
</div>
    
25.04.2018 / 19:33