1

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

2
  • Are you wanting to apply this to all child in the tree or just the subchild? Commented Dec 11, 2018 at 12:25
  • stackoverflow.com/questions/53720313/… check this out. Commented Dec 11, 2018 at 12:37

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.