I want to attach keypress
and focusout
event handlers to a paragraph inside contenteditable div
.
The following code doesn't seem to work:
<div contenteditable="true">
<p id="p1">Test</p>
<p id="p2">Test</p>
<p id="p3">Test</p>
</div>
$('#p1').bind('keypress', function(e) {
alert('keypress');
});
$('#p1').focusout(function(e) {
alert('focusout');
});
Basically the contenteditable
is the one that will respond to events dispatched from the inner Nodes. If we get the caret position and than target it's range's parentNode - than we can retrieve the desired ID
$('[contenteditable]').on('keypress focusout', function(ev) { var node = window.getSelection().getRangeAt(0).commonAncestorContainer; var nodeParent = node.parentNode; // Do something if parent node ID is "p1" if( nodeParent.id === "p1") { console.log( nodeParent.id +' '+ ev.type ); // or whatever you need to do here } });
<div contenteditable="true"> <p id="p1">TestP1 do someting on keypress</p> <p id="p2">TestP2 is Not Interesting</p> </div> <script src="//code.jquery.com/jquery-3.1.0.js"></script>
There's an answer over here: https://stackoverflow.com/a/18772205/2100255
Basically, you need to wrap your inner contenteditables with non-contenteditables. The event fires off the node which declares contenteditable=true.
I have altered the solution, Refer the latest fiddle
$(document).on('keypress', '#p1[contenteditable="true"]', function(e) {
alert("test");
});
You can do it as below Instead of click event you can change it to event on which you want to track the change.I am using click for example
$("div").click(function(e){ console.log($("#"+$(e.target)[0].id).text()); });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.