Reputation: 3696
I have some contenteditable paragraphs that I would like to remove if the delete or backspace key is pressed. I've written the following script for this:
$(document).on('keyup', 'p[contenteditable="true"]', function(e) {
if(e.which == 13) {
e.preventDefault();
$(this).after('<p contenteditable = "true">New Paragraph</p>');
$(this).next('p').focus();
} else if((e.which == 8 || e.which == 46) && $(this).text() == "") {
e.preventDefault();
$(this).remove();
$(this).previous('p').focus();
};
});
I would like to focus on the previous paragraph after removal but I don't believe I can do this as this
no longer exists. I've also tried putting the focus
before remove
however it appears to change the value of this
.
Upvotes: 0
Views: 199
Reputation: 5351
Try something like this:
$(document).on('keyup', 'p[contenteditable="true"]', function(e) {
if(e.which == 13) {
e.preventDefault();
$(this).after('<p contenteditable = "true">New Paragraph</p>');
$(this).next('p').focus();
} else if((e.which == 8 || e.which == 46) && $(this).text() == "") {
e.preventDefault();
var prev = $(this).prev('p');
$(this).remove();
prev.focus();
};
});
Also worth noting that .previous()
is not a jQuery method, I believe the method you are looking for is .prev()
Upvotes: 3