How to prevent my jQuery textarea Focus event from firing repeatedly for ulimted times in a row

336 Views Asked by At

I have something like the basic JavaScript jQuery code below that is only called once in my project code however it alerts 100+ times when my textarea attached to the event is focused by clicking my mouse cursor into it!

projectTaskModal.cache.$cmtTextarea.on('focus', function() {
    alert('ON FOCUS EVENT');
});

My goal is to fire this event 1 time as it is used to simply add a CSS class and a few other tasks which are then removed after my Form is posted. A form is posted with an AJAX request and then it is ready for the next Focus action to trigger the event again. However as mentioned it fires 100+ times each time I give it focus! Not good, please help!

2

There are 2 best solutions below

1
On BEST ANSWER

You would be better of with a flag. Try this.

var isEventTriggered = false;
projectTaskModal.cache.$cmtTextarea.on('focus', function () {
    if (!isEventTriggered) {
        alert('ON FOCUS EVENT');
        isEventTriggered = true;
    }
});
0
On

have you looked at .one()

try

projectTaskModal.cache.$cmtTextarea.one('focus', function() {
    alert('ON FOCUS EVENT');
});

and you might need to attached it back after Form is posted.