1

I have a problem with jquery and the .click() function, when clicking on a <li data-link-url="..."> element, that shares the data-link-url attribute.

This is my HTML structure:

<nav class="fullListHover">
  <ul>
    <li class="oneHub">
      <a href="... /suppliers/technology.html"></a>
      <ul>
        <li data-link-url="... /templateA.html">
          <ul>
            <li data-link-url="... /templateB.html"></li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>       
</nav>

And this is my jquery click() function:

<script type="text/javascript">
  $("[data-link-url]").click(function(){
      window.location.href=$(this).attr("data-link-url")
  });
</script>

When I click on the li-tag with ".../templateB.html" I get redirected to ".../templateA.html". So I debugged the whole thing and logged the $(this) variable. When I clicked on ".../templateB.html" the output was:

.../templateB.html
.../templateA.html

It seems like, the .click() function runs a second time.

How can I select just the templateB or prevent the click function to run a second time ?

P.S.: I hope my question is understandable. English isn't my primary language.

1 Answers1

3

Your issue is because you have nested li elements with the data-link-url attribute, hence the click handler is invoked once for each element in the hierarchy as the event bubbles up the DOM. To fix this, call stopPropagation() in the event handler:

$("[data-link-url]").click(function(e) {
    e.stopPropagation();
    window.location.href = $(this).data('link-url');
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339