0

I just want the keyup even to work on child but not on parent, just showing as example below that it works on parent but not on child.

Here is my jQuery:

// This works
$('#editor').on('keyup change', function(){
  console.log('keyup event works on Parent');
});

// This doesn't do anything
$('#editor').on('keyup change', '.js-selected-text', function(){
  console.log('How to make keyup event work for child');
});

Here is my markup, and class for child js-selected-text will be added dynamically, so I am using .on() to bind.

<div id="editor" class="wysihtml5-editor" contenteditable="true">Lorem <span class="js-selected-text">Ipusum</span> dolo solo polo</div>
Syed
  • 15,657
  • 13
  • 120
  • 154

2 Answers2

0

By using DOMSubtreeModified you can do this.

 $("#editor").on('DOMSubtreeModified', ".js-selected-text", function () {
  console.log('How to make keyup event work for child');
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="editor" class="wysihtml5-editor" contenteditable="true">Lorem <span class="js-selected-text">Ipusum</span> dolo solo polo</div>
4b0
  • 21,981
  • 30
  • 95
  • 142
  • thanks for answering, your code works but has issue for me. I am fetching all the `.js-selected-text` that in `#editor`, the class `.js-selected-text` and `span` get wrapped to the text when I click a button. Somehow, now when I click the button, the text within `.js-selected-text` is being fetched twice. Is there a way to just keep it for keyboard event or anything else than `DOMSubtreeModified` – Syed Apr 17 '17 at 07:23
0

Try the following code

Take the look at Detect keyup event of contenteditable child whose parent is a contenteditable div

HTML

<div id="editor" class="wysihtml5-editor" contenteditable="true">
    Lorem 
    <span contenteditable="false">
        <span class="js-selected-text" contenteditable="true">
            Ipusum
        </span>
    </span> 
    dolo solo polo
</div>

Jquery

// This works
$('#editor').on('keyup change', function(){
  console.log('keyup event works on Parent');
});

// This doesn't do anything
$('#editor').on('keyup change', '.js-selected-text', function(e){
  console.log('How to make keyup event work for child');
  e.stopPropagation();
});

Here is the working jsfiddle:https://jsfiddle.net/gg456p7a/

Community
  • 1
  • 1
selvarajmas
  • 1,623
  • 13
  • 20
  • thanks for your answer. As mentioned by me, `js-selected-text` being added dynamically and assume that I have no access to add extra wrapping ``. – Syed Apr 17 '17 at 07:27