Reputation: 191
I have a function that wraps selected text in a span when the delete key is pressed. The class of the span is red with a line-through, to show it's been "deleted."
CSS:
.deleted {
text-decoration:line-through;
color:red;
}
JavaScript:
$(document).keydown(function(e) {
(e) ? keycode = e.keyCode : keycode = event.keyCode;
if (keycode == 8 || 46) {
var span = document.createElement("span");
span.className = "deleted";
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(span);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
});
This is a contenteditable
text, so when I press the delete key, naturally it deletes the selected text, but still creates the <span>
element. Is there any way to disable the traditional function of the delete key so that the text remains but still wraps with the <span>
?
Upvotes: 0
Views: 636
Reputation: 2163
You need to stop the the default action of the event.
You need to add e.preventDefault() into your code that insure that default action of the event will not be triggered.
$(document).keydown(function(e) {
e.preventDefault();
(e) ? keycode = e.keyCode : keycode = event.keyCode;
if (keycode == 8 || 46) {
var span = document.createElement("span");
span.className = "deleted";
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(span);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
});
Upvotes: 0
Reputation: 3178
e.preventDefault()
should work.
Also, you should use the <del>
HTML element instead of <span>
with a class attached.
Test out this testcase: https://jsfiddle.net/jdshq796/
Upvotes: 1