0

I've got the following HTML structure.

<ul class="nav">
    <li class="header">Sites</li>
    <li><a href="#" class="showSite" >Site A</a></li>
    <li><a href="#" class="showSite" >Site B</a></li>
</ul>

and I'm using this jQuery

$("body").on('click', '.nav', function( ) {
    console.log ( 'nav clicked' )
    // other code //
})

When the element with class nav is clicked the jQuery runs, but I don't want it to run if one of the href links is clicked.

I've added console.log ( this ) to jQuery and it always shows the nav element is clicked even when the href is clicked.

Just to add to this I do have some other jQuery that is triggered when .showSite is clicked and that is running fine. I just don't want the .nav jQuery to run when the href is clicked.

Is it possible to not have the jQuery run when I click on the href's ?

Thanks

Update I think I may have solved this.

$("body").on('click', '.nav', function(e) {
    console.log ( 'nav clicked' )
    if ( $(e.target).attr('class') == 'showSite' ) return false
    // other code //
})
Tom
  • 1,436
  • 24
  • 50
  • 1
    Your `a` clicks are *bubbling* up to the .nav. You can add an event handler on the `a` and cancel events or you can check `currentTarget`. Here's an answer which explains the difference (other answers also exist on SO) https://stackoverflow.com/a/31866151/2181514 – freedomn-m May 05 '23 at 10:36
  • I think I may have resolved this. I'll update my question – Tom May 05 '23 at 10:39
  • probably best way to do it would be to add a click event to the links and [stop the propagation](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation) – Pete May 05 '23 at 10:44
  • 1
    Does this answer your question? [How do I prevent a parent's onclick event from firing when a child anchor is clicked?](https://stackoverflow.com/questions/1369035/how-do-i-prevent-a-parents-onclick-event-from-firing-when-a-child-anchor-is-cli) – Pete May 05 '23 at 10:46
  • Simply stop the event propagation, so it doesn't bubbles up. You can use e.stoppropagation() – Developer May 05 '23 at 11:44

1 Answers1

0

As suggested in the comments, you can prevent event bubbling by calling stopPropagation() on the click event of anchor tag.

$("body").on('click', '.nav', function(event) {
  console.log('nav clicked');
  // other code //
})

$("body").on('click', '.nav a', function(event) {
  event.stopPropagation();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="nav">
  <li class="header">Sites</li>
  <li><a href="#" class="showSite">Site A</a></li>
  <li><a href="#" class="showSite">Site B</a></li>
</ul>
Sachin Som
  • 1,005
  • 3
  • 8