I would like to be able to click on a list item and then hit the backspace key to delete it. How would I do this with jQuery?
$('<li>Click Me</li>')
.appendTo('#list')
.click(function(){
$(this).addClass('delete');
$(this).focus(); // doesn't seem to do anything maybe??
})
.keypress(function(e){
// this event handler doesn't fire
var key = (e.keyCode ? e.keyCode : e.which);
if (key === 8) {
if ($(this).hasClass('delete'))
$(this).remove();
}
});
Here’s my jsfiddle:
Looks like I can’t attach a keypress event to a list item.
You’ll need to try having the key handler on the document level. Also, it’s safer to use ‘keydown’ instead of ‘keypress’. Working example: http://jsfiddle.net/DwX4e/