Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.remove event triggers .blur event - how to escape that?

Tags:

jquery

I have the .blur() event bound to an element. Whenever I remove an element with $(elem).remove() method, the .blur event is triggered for the same element. Here is jsFiddle - to see the case click on the blue div and press any key.

Here is the code: HTML:

<div id="container"></div>
<ul id="tr"></ul>

CSS:

#container {
    width:100px;
    height:100px;
    background:blue;
    position:relative;
    cursor:pointer;

} JS:

$("#tr").on('keydown', '#ti', function() {
    $(this).remove();
});
$("#tr").on('blur', '#ti', function() {
    alert('blur is triggered');
});
$('#container').on('click', function() {
 var item = '<li id="ti" contenteditable="true"></li>';
 $("#tr").append(item);
 $("#ti").last().focus();
});

How can I prevent the .blur event if an element is removed? Or maybe how can I know that the event is triggered my element's deletion?

like image 748
Max Koretskyi Avatar asked Oct 31 '25 22:10

Max Koretskyi


2 Answers

Remove the blur event before removing the item

$("#tr").on('keydown', '#ti', function() {
    $(this).off('blur');
    $(this).remove();
});
like image 72
Roger Barreto Avatar answered Nov 04 '25 21:11

Roger Barreto


You can simply call the unbind-function before you remove the element. That should solve your problem. Code:

$(elem).unbind();

This will unbind any action bound to the object.

like image 27
Patrick Kostjens Avatar answered Nov 04 '25 20:11

Patrick Kostjens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!