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

Asked

Viewed 52 times

1

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

To illustrate, it follows 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);
  });

});

1 answer

1


You need to find just the div that is in the same div father. The way you’re doing, you’re applying the .toogle to all with class .divQueAparece. You can do it the way 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>
<div class='pai'>
    <i icon dropdown class='elementoDisparo'>clique-me1</i>
    <div class="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 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>
<div class='pai'>
    <i icon dropdown class='elementoDisparo'>clique-me1</i>
    <div class="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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.