When I click on a div element of a certain class, I change contenteditable to true. onblur of that clicked div I want it to alert something. The first time that I blur the div, it works fine, but after that it shows the same alert twice. So the first time, it alerts once. The second time, it alerts twice, etc.
What am I doing wrong?
content = $('#content');
content.delegate('div', 'click', function(event){
$(this).attr('contenteditable', 'true');
$(this).focus();
$(this).bind('blur', function(){
alert('blur');
});
});
Example: http://jsfiddle.net/W8que/4/
You’re binding the blur again on each click. Each bind is new and they are stacking. Use
.delegate()(or.on())for the blur function also.fiddle: http://jsfiddle.net/W8que/11/
code:
Since the fiddle was already using jQuery 1.7.x, I went ahead and swapped out
.delegate()for the more up-to-date.on(). Slipped in a few other things like caching$(this)and didn’t bother passing the event into the function since there’s nothing we need topreventDefault()orstopPropagation()on.