Jack Vawdrey Jack Vawdrey - 1 month ago 18
HTML Question

Wrap with span if text is selected

I am using the following function to wrap highlighted text with a

<span>
when the backspace/delete key is hit.



$(document).keydown(function(event) {
var selection = document.getSelection();
typoNumber++;
if (event.keyCode == 8 || event.keyCode == 46) {
event.preventDefault();
var span = document.createElement("span");
span.setAttribute('id', 'typo' + typoNumber);
span.className = "deleted typo";
span.setAttribute('contenteditable', 'false');
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(span);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
});

.deleted.typo {
background: rgba(100,100,100,0.25);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>Here is text to experiment with.</div>





I only want the function to run if there is text selected (so that I don't get a bunch of empty
<span>
elements). I tried changing the first
if
statement to the following:

if (selection !== '' && event.keyCode == 8 || event.keyCode == 46) {


but that didn't work. Any ideas?

Answer

Changing your condition to this should help you:

if(
  selection.anchorOffset !== selection.focusOffset 
  && 
  (event.keyCode == 8 || event.keyCode == 46)
) 

Fiddle: https://jsfiddle.net/34L49xLr/