javascript - Trigger event on parent originating, bubbling up from child -
if have <div class="timely"></div> containing table, in table <th class="prev"><i>previous</i></th>...chrome dev tools there event listener on <th>, firefox dev tools points out not on <th>, parent .timely, chrome points out when viewing in handler event.
what trying replicate happens on click, happen on keyup. doesn't seem simple as, in jquery:
$('.timely th').each(function(){ $(this).on('keyup', function(){ $(this).trigger('click'); }); }); because event handler on .timely , listening event bubbled when executing code.
how can replicate click event on keyup of .timely context of bubbling <th>?
first, note there's no reason each loop (unless you're doing else in haven't shown). remember jquery set-based, $("selector").on(...) sets handler on elements in set.
re question: accept event argument , use target property element on trigger:
$('.timely th').on('keyup', function(e) { $(e.target).trigger('click'); }); or if want handle on .timely instead of on th in .timely, change selector , use delegating form (assuming want th elements):
$('.timely').on('keyup', 'th', function(e) { $(e.target).trigger('click'); }); it's tricky keyup on th element, of course; way coming mind put input element in th keyup bubbles:
$('.timely th').on('keyup', function(e) { console.log("keyup"); $(e.target).trigger('click'); }); $('.timely th').on('click', function(e) { console.log('click'); }); <div class="timely"> <table> <tbody> <tr> <th> <input type="text"> </th> </tr> </tbody> </table> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> you haven't said why want trigger click on keyup, if it's run click event handler, don't recommend doing that. instead, use same function both keyup , click handler. can hook multiple events space-delimiting them in .on (.on("click keyup", ...)), or use named function , refer hook click , keyup handlers.
chrome dev tools there event listener on
<th>, firefox dev tools points out not on<th>, parent.timely
if don't want see handlers attached ancestors, untick ancestors box in event listeners tab:
but note in example code, handler on th, not ancestor .timely element.

Comments
Post a Comment