user1095749
user1095749

Reputation: 3

jQuery focusout event repeating itself issue

This thing works, but each time I am clicking the element I want to get, it's "count" the clicks and then print log comments for the same number of total clicks.

For example, if I click the element 3 times in a row (and then clicking outside to trigger the focusout), it prints 3 log comments, if I then click 2 more times (and outside again) it prints 5 log comments.

And I want to get only one log comment each time when I am clicking outside the element.

Help anyone?

 $("#main-wrapper").click(function (e) {
    var contenteditable = $(e.target).attr('contenteditable');
    if (contenteditable == 'true') {
        $(e.target).focusout(function() {
            var content = $(this).html();
            console.log("get: " + content);
        });
    };          
});

Upvotes: 0

Views: 1001

Answers (2)

laurens peeters
laurens peeters

Reputation: 555

Try unbinding the event.

$("#main-wrapper").click(function (e) {
var contenteditable = $(e.target).attr('contenteditable');
if (contenteditable == 'true') {
    $(e.target).unbind('focusout').focusout(function() {
        var content = $(this).html();
        console.log("get: " + content);
    });
};          
});

Upvotes: 2

Linus Thiel
Linus Thiel

Reputation: 39223

You are attaching a new focusout event handler each time you handle a click. These event handlers are not replaced, but added, and each event handler is executed when the event is triggered. That's why you get the same number of logged messages as previous clicks.

You should be able to specify the focusout handler just once, but how you want it to be triggered is of course depending on what you want to accomplish.

$("#main-wrapper").focusout(function (e) {
  var contenteditable = $(e.target).attr('contenteditable');
  if (contenteditable == 'true') {
    var content = $(this).html();
    console.log("get: " + content);
  }          
});

Upvotes: 1

Related Questions