Javascript – Function run multiple times on textfield focus

javascriptjquery

I want to call a function when I have a textfield focused and then unfocus it (whether I press TAB or click elsewhere with the mouse) and I used this code:

 $("#settings_view #my_profile_div input").focus(function() {
        $(this).blur(function() {
            change_my_profile();
        });
    });

When I first run it (have a field focused then unfocus it) it runs one time as expected. However, the second time it calls the function change_my_profile twice. The third time it ran 3 times and so on.

What is the problem here and how do I solve it? (I tried with 'throw' after change_my_profile and then it only ran one time, but I want to locate the problem anyway).

Best Answer

it is binding a blur event every time a focus event is initiated, that's why you are getting multiple executions

try

$(this).bind("blur",function(){
  change_my_profile(this);
})

and then in your change_my_profile function do the following

function change_my_profile(el){
  $(el).unbind("blur");
  //rest of the change_my_profile code goes here
}