Ben Ben - 2 months ago 18
Javascript Question

onclick function exclude div contents

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.

Answer

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