1

I have the following function:

function viewdwable(dwableid) {
  $("#modal-body2").html('Temporary loading message..');
  $("#myModal").fadeIn(300);
  $.ajax({
    url: 'scripts/viewdwablehome.php',
    data: { "currentNumber": dwableid, "usersid": usersid },
    type: 'post',
    dataType: "json",
    success: function(data) {
      $('#modal-body2').html(data['cntent12']);
    }
  });    
}

This activates when clicked:

<div class="postfeed2" onclick="javascript:return viewdwable(' . $id . ');">
  <a href="javascript:void(0)" onclick="javascript:return like(' . strip_tags($id) . ');">Text linked here</a>
</div>

The problem is I have another onclick link within the div. When that onclick is clicked I don't want it to also fire the div onclick.

Peter
  • 2,796
  • 1
  • 17
  • 29
Ben
  • 369
  • 1
  • 3
  • 14

2 Answers2

2

Fire your function inside a proper event handler, so you can use event.stopPropagation() for the inner element. This will prevent the event from bubbling up the DOM.

$('.postfeed2').on('click', function(){
    alert('clicked outer');
});

$('a').on('click', function(e){
    e.stopPropagation();
    alert('clicked inner');
});

Example

Community
  • 1
  • 1
empiric
  • 7,825
  • 7
  • 37
  • 48
  • The div postfeed2 is part of an array which means it appears multiple times and why I didn't use this format. Do you have an example using onclick specifically? – Ben Sep 08 '16 at 18:59
  • Instead of have the variable `$id` as a function parameter you can attach it as e.g. a ´data-´ attribute and referencing to it inside the event-handler – empiric Sep 08 '16 at 19:02
  • Could you show me how to add it and particularly reference it. I've never used that kind of attribute before. Thanks! – Ben Sep 08 '16 at 19:05
  • @Ben Have a look at [this](https://jsfiddle.net/kqLsv1sh/) example. You can acces the data-attribut with `.data('')`. – empiric Sep 08 '16 at 19:09
  • Yep @empiric think I can work it out from there. Market correct. – Ben Sep 08 '16 at 19:10
0

You need to use stopPropagation.

Read more about event.stopPropagation()

Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64