2

I'm trying to remove the class .words from this HTML, whenever it's clicked on it or if a keypress happens over it.

<div id="content" contenteditable="true"> Here are <span class="words" id="whatever">some</span> words </div>

I've tried

$('.words').click(function() { $(this).remove(); });

and more, which work except when I click on another word and cycle over .words using left or right key (since it is content editable). I'd like it to be removed as soon as the the cursor is over the class. Thanks.

Squirrl
  • 4,909
  • 9
  • 47
  • 85
  • I think this question has been answered before? http://stackoverflow.com/questions/1197401/how-can-i-get-the-element-the-caret-is-in-with-javascript-when-using-contentedi – Nick Grealy Feb 13 '14 at 23:01

1 Answers1

2

Something like this?

var words = $('.words')[0]    

$('#content').keyup(function(){    
    if (words == getSelectionStart()){
        $(words).remove()   
    }
})

function getSelectionStart() {
   var node = document.getSelection().anchorNode;
   return (node.nodeType == 3 ? node.parentNode : node);
}

Example: http://jsfiddle.net/nickg1/ttMJW/1/

Nick Grealy
  • 24,216
  • 9
  • 104
  • 119