Home > Mobile >  How to make js only affect element of concern?
How to make js only affect element of concern?

Time:12-06

I have this super easy JS that does one thing; namely toggles an open class on a specific element in the page. Problem is that I have 4 repetitions of both the .clickSlide element and the .sub_menu element and when I click one of the elements to trigger the code all elements gets the open class. Only the element of concern, out of the 4, should get the open class.

My best guess is I am missing some sort of this in the JS. But I am open to solutions on this one!

jQuery(document).ready(function($) {
  $(".clickSlide").click(function() {
    $(".sub_menu").toggleClass("open");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <ul >
    <li >
      <ul >
        <li></li>
      </ul>
    </li>
  </ul>
</div>

<div >
  <ul >
    <li >
      <ul >
        <li></li>
      </ul>
    </li>
  </ul>
</div>

<div >
  <ul >
    <li >
      <ul >
        <li></li>
      </ul>
    </li>
  </ul>
</div>

<div >
  <ul >
    <li >
      <ul >
        <li></li>
      </ul>
    </li>
  </ul>
</div>

CodePudding user response:

the .sub_menu selector in your jQuery code is selecting all elements with the sub_menu class. This means that when you call the toggleClass method, it is applied to all of the selected elements, which is why all of the sub_menu elements are getting the open class when you click any of the clickSlide elements.

To fix this, you can use the $(this) selector in your code, which refers to the element that was clicked. This will allow you to select only the sub_menu element that is associated with the clicked clickSlide element, so that only that element gets the open class. Here is an example of how you could do this:

jQuery(document).ready(function($) {
    $(".clickSlide").click(function(){
        $(this).next(".sub_menu").toggleClass("open");
    });
});

CodePudding user response:

So the solution (based on Anass Kartit answer) was this:

jQuery(document).ready(function($) {
    $(".clickSlide").click(function(){
        $(this).children(".sub_menu").toggleClass("open");
    });
});
  • Related