N.J.honey
N.J.honey

Reputation: 54

jquery click event on nested elements with same class

I am newbie for jquery. I have nested li with same name. And I want to set left position of div with class open according to clicked li level. But when I click inside li it take position of first.

Here is my code

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="open">
  <ul>
    <li class="child">
      <a href="#">link1</a>
      <ul>
        <li class="child">
          <a href="#">menu link1</a>
        </li>
      </ul>
    </li>
  </ul>
</div>
<script>
  $(".child").on("click", function() {
    var l = $(this).parents('ul').length
    var a = 101 * l;
    $(".open").css({
      "left": "-" + a + "%"
    })
  })
</script>

Thanks in advance

Upvotes: 1

Views: 840

Answers (3)

MrMaavin
MrMaavin

Reputation: 1741

You can stopt the propagation with event.stopPropagation();. I added a console.log() so that you see what is clicked.

$(".child").on("click", function(event) {
  event.stopPropagation();
  var l = $(this).parents('ul').length
  var a = 101 * l;
  console.log("click: " + $(this).find(">a").text());
  $(".open").css({
    "left": "-" + a + "%"
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="open">
  <ul>
    <li class="child">
      <a href="#">link1</a>
      <ul>
        <li class="child">
          <a href="#">menu link1</a>
        </li>
      </ul>
    </li>
  </ul>
</div>

Upvotes: 1

Thorvarium
Thorvarium

Reputation: 118

The problem is that the click is happening in both when you click the inner li, you can use stopPropagation inside the event to prevent that

Upvotes: 2

mtizziani
mtizziani

Reputation: 1016

you have to disable the bubbling

$(".child").on("click", function(event) {
    event.preventDefault(); // diasble default action
    event.stopPropagination();  // disable bubbling to parent event
    var l = $(this).parents('ul').length
    var a = 101*l;
    $(".open").css({
      "left": "-" + a + "%"
    })
  })

not tested

Upvotes: 0

Related Questions