I dynamically generate <p> tags inside <div contenteditable=true> , but the event handler that I have installed to catch keyup events coming from <p> tags does not capture them.
HTML
<div class="note"> <p contenteditable="true"></p> </div> <div class="note" contenteditable="true"></div> <div id="output"></div>
Js
$(document).ready(function() { $(".note").keyup(function(evt) { $("#output").append("<br/>note tag keyup"); // Surround paragraphs with paragraph tag $(this).contents().filter(function() { return this.nodeType === 3; }).wrap('<p class="test"></p>'); }); $(".note").on("keyup", "p", function(evt) { $("#output").append("<br/>p tag keyup"); }); });
Fiddle: https://jsfiddle.net/mibacode/axgccwoq/3/
The first div element demonstrates that I can successfully catch the keyup event from the paragraph tag generated at loading. The second div shows that my dynamically generated paragraphs are not firing (or JQuery just can't catch) the keyup event.
Edit:
The problem / error seems to be related to how paragraph tags are generated and added to the DOM in this part of the code:
$(this).contents().filter(function() { return this.nodeType === 3; }).wrap('<p class="test"></p>');
I believe that for some tag the <p> not appended properly, so the DOM does not recognize it or does not know that it exists.
Edit 2: I replaced the jQuery function, which inserts new paragraph tags using vanilla JS in the hope that this might solve my problem, however it is not.
New code:
var textNode = null; var nodes = this.childNodes; for (var i = 0; i < nodes.length; i++) { if (nodes[i].nodeType === 3) { textNode = nodes[i]; break; } } if (textNode) { var p = document.createElement("P"); var attr = document.createAttribute("contenteditable"); attr.value = "true"; p.setAttributeNode(attr); p.addEventListener("keyup", function() { $("#output").append("<br/>Special paragraph click!"); }); p.innerHTML = textNode.nodeValue; var parent = $(this)[0]; parent.insertBefore(p, textNode); parent.removeChild(textNode); }
This seems to be due to the way JS handles events fired from elements in content elements.