differentiate the clicks between parent and child using javascript/jquery -
i have 2 elements nested called blanket , blanket-content , want recognize clicks done parent alone.
<div id="blanket"> <div id="blanket-content"></div> </div>
the issue i'm having when i'm clicking child triggering parent on click. i've tried different methods yet unsuccessful. have tried these play around code;
$('#blanket').on('click', function(ev) { alert(ev.currenttarget.id); // });
^ triggers click on div normal , state parent id when child clicked.
$('#blanket-content').on('click', function(ev) { alert(ev.currenttarget.id); });
^ doesn't trigger anything
what want achieve when click on blanket-content nothing happen, when click on blanket want something.
one easy solution stop event propagation in click handler of blanket-content
, trigger parent element's click handler.
you can use event.stoppropagation() that
$('#blanket').on('click', function(ev) { alert(ev.currenttarget.id); // }); $('#blanket-content').on('click', function(ev) { ev.stoppropagation() });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="blanket">blanket <div id="blanket-content">blanket-content</div> </div>
another solution(why) check whether click happened in blanket-content
element inside blanket
click handler
$('#blanket').on('click', function(ev) { if (!$(ev.target).closest('#blanket-content').length) { alert(ev.currenttarget.id); // } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="blanket">blanket <div id="blanket-content">blanket-content</div> </div>
Comments
Post a Comment