jQuery - Trigger event only in the clicked element

Asked

Viewed 29 times

0

Hello, I’m a beginner in jquery and I have the following problem: I have the same element that repeats several times on the page, and when I click on it I need to perform a function. But the function is being executed for all elements that have this class. I would like the function to be executed only for the element I clicked, regardless of having others with the same class. See my jquery here:

const details = $('.open-details');
const additional = $('.additional-texts');
details.each(function(){
 $(this).on('click', function(event){
  if (additional.hasClass('open')) {
     additional.slideUp("slow");
     $('.arrow').css('transform', 'rotate(0deg)');  
  } else {
     additional.slideDown("slow");
     $('.arrow').css('transform', 'rotate(180deg)');  
  }
  additional.toggleClass('open');
 });
});

I would like when you click on the div 'Details' to trigger the rest of the function. I did so but it runs for all Divs 'Details' present on the page. Any help is welcome :)

1 answer

2

The behavior that reports in the question is strange. Make sure you are looking for the right elements and if there is no other part of your code changing the desired behavior. That said, how do you need the event is triggered only in the clicked element, you can attach an event to it using a more specific selector, just in the desired element:

$(document).ready(function () { 
    // o identificador abaixo pode ser um ID, um seletor mais específico, etc.
    $('#div1').click(function () { /*...*/ });
    $('#div2').click(function () { /*...*/ });
    $('#div3').click(function () { /*...*/ });
});

If you prefer, you can do this by assigning a onclick event directly in the HTML tag of your element:

<div onclick="evento()">...</div>

If you notice that events are being triggered on several other elements (such as "parent" elements), you can prevent their propagation with the method stopPropagation or stopImmediatePropagation (cancelBubble in IE):

event.stopPropagation(); // ou stopImmediatePropagation

As I mentioned the strange behavior, follow a snippet which selects elements in the same way (by class). Try switching event selections and assignments and see what works best for your use case:

$(document).ready(function () {
  $('.div').each(function () {
    $(this).click(function () {
      if ($(this).css('color') == 'rgb(255, 0, 0)') {
          $(this).css('color', 'rgb(0, 0, 0)');
        } else {
          $(this).css('color', 'rgb(255, 0, 0)');
        }
    })
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="1" class="div">Div 1</div>
<div id="2" class="div">Div 2</div>
<div id="3" class="div">Div 3</div>

I hope I’ve helped in some way.

Browser other questions tagged

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