How to trigger a function once, after focusin on input element?

2.4k views Asked by At

I want to trigger a function only one time at focusin in a element input. The follow code calls the function in a infinite loop.

<input type="text" class="dateRangeEducLev">
$(document).on("focusin",".dateRangeEducLev",function(e){    
    alert("focusIn");
});

I could change the event to "onClick" but it would calls the function each time the user click in a input element even if the input element is already selected. This is not desirable.

I was trying to workaround this problem preventing propagation but it is not working. this is the code:

$(document).on("focusin",".dateRangeEducLev",function(e){    
    alert("focusIn");
    e.stopPropagation();
});

http://jsfiddle.net/r1b06udo/1/

Any idea in how to stop propagation or restrict the function to be called only once?

Update: If I use off() or one() will stop to call the function forever until the browser refresh. Another problem is if I have more then one element with same class the function will be disabled for them.

http://jsfiddle.net/r1b06udo/2/

I have a new update. I choose unbind and bind. If you see it will work for the first round. But if you still focusin they will do nothing, but if you still focusin it will work for a wile.

http://jsfiddle.net/456at7y8/

2

There are 2 answers

3
Claudio Redi On BEST ANSWER

You can call off on your focusin handler to disallow this handler to be called again

$(document).on("focusin",".dateRangeEducLev",function(e){    
    alert("focusIn");
    $(document).off("focusin",".dateRangeEducLev");
});

Calling one is the other option as other pointed out. The problem is that I'm not aware that you can use it with delegated events as you are doing with on. That's why I suggested this approach.

Delegated events seems unnecessary according what you show, in any case I tried to keep it just in case.

0
yugi On

use one() to bind the event

$(".demo1").on("focusin",function(e){    
    alert("focusIn");
    $( this).unbind( "focusin" );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="dateRangeEducLev demo1"/>
    
<input type="text" class="dateRangeEducLev demo1"/>
<input type="text" class="dateRangeEducLev demo1"/>