Forum Moderators: open

Message Too Old, No Replies

How to get current node with keydown

event.target works with click, but not keydown

         

csdude55

7:49 am on Aug 6, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I've been working with this script, and while it works fine with click, it doesn't work with keydown. I don't get any errors, the while() loop just doesn't trigger.

$('div').on('keydown click', function(e) {
var node = e.srcElement || e.target;

while (node !== this) {
if (node.nodeName == 'B')
$('[data-richcont="B"]').removeClass('richbuttonOff').addClass('richbuttonOn');

node = node.parentNode;
}
});

// HTML
<div data-richcont="B">Bold</div>

<div contenteditable="true">
<b>Test</b> Test
</div>


When I click on <b>Test</b> with the mouse the while() loop triggers, but when I use the arrows to move over to it the loop doesn't trigger at all. So for whatever reason, when I use the keys I think that node is equal to the outermost node, 'DIV', instead of the innermost node, 'B'.

So how do I find the innermost node while using keydown?

csdude55

2:14 am on Aug 9, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I figured it out... change node to:

var node = getSelection().anchorNode.parentNode;


And while (node !== this) didn't quite work, I had to use an identifier for div. So in my case, where I was using <div contenteditable="true">, I did:

while (node.getAttribute('contenteditable') !== 'true') { ... }


Hopefully this will help future coders! Cause even after I figured out the solution, I still couldn't find this anywhere on Google.