Getting keydown event parent element, jQuery -
i trying identify immediate parent (paragraph element) of cursor within contenteditable div looks this:
<div id=base> <div ce='1' contenteditable='true'> <p id='unique'>paragraph one</p> <p>paragraph two</p> </div> </div>
if bind .click event 'ce' div, event.currenttarget reported paragraph in click occurs. track cursor need use .keydown event
$('#base').on({ keydown: function(event) { mylog(' nodename: '+event.currenttarget.nodename); }, // following selector event triggered cursor // anywhere in 'ce', , .currenttarget 'ce' div. }, '[ce]'); // selector event never triggered regardless of cursor position }, '#unique');
why event not being triggered, , how can achieve aim?
i don't think can element event object event fired on #base , #base target (and not textnode or paragraph).
you use current selection container (textnode) contains cursor @ moment when event occurs , use container search paragraph.
this this:
$('#base').on({ keydown: function(event) { // current selection var selection = window.getselection(); if (selection.rangecount === 1) { // container of cursor var textnode = selection.getrangeat(0).startcontainer; // use jquery paragraph console.log($(textnode).parents('p')); } } });
this simple (not cross-browser) example (tested in firefox). real code have more checks current cursor position. make life easier have @ rangy:
https://code.google.com/p/rangy/
this library handles selections.
Comments
Post a Comment