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.

3
  • Not an exact duplicate, but there are likely others: stackoverflow.com/questions/387736/… Commented Nov 14, 2016 at 17:22
  • click events bubble. Commented Nov 14, 2016 at 17:23
  • I must have looked for the wrong keywords, because I didn't find any suitable answer for my problem. Thank you though! Commented Nov 15, 2016 at 9:16

1 Answer 1

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');
});
Sign up to request clarification or add additional context in comments.

3 Comments

Sample fiddle with stopPropagation - remove the line to see the event bubble: jsfiddle.net/7wto6hrh
Just out of curiosity: why using .data() instead of .attr() ? Is it because of IE problems with .attr() ?
In most cases it's faster as it's using jQuery's internal cache instead of accessing the DOM.

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.