1

I have a div containing a link, when I click on the container, I have some AJAX functionality, but I also have a link in the div, which I want to function as a normal link and not trigger the click handler.

<div class="box">
    Lorem ipsum dolor sit amet...
    <a href="/actions/something/">Edit</a>
</div>

$('.box').on('click', function() {
    $.ajax({
        ...
    });
});

I attach the handler to all of the other text in the container, but that wouldn't fire the handler if I click on the box background.

Echilon
  • 10,064
  • 33
  • 131
  • 217
  • 1
    attach another event handler for anchor and use [`event.stopPropagation()`](https://api.jquery.com/event.stoppropagation/) – Satpal May 16 '17 at 09:04

1 Answers1

0

You can either detect the clicked element in the .box event handler and then run whatever logic is required:

$('.box').on('click', function(e) {
  if (e.target.tagName !== 'A') {
    $.ajax({
     // ...
    });
  }
});

Or alternatively you can place a separate event handler on the a element which stops the event propagating to the .box:

$('.box a').click(function(e) {
  e.stopPropagation();
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339