Luca Detomi
Luca Detomi

Reputation: 5716

jQuery: remove a specific click handler preserving others

I have a form with some fields, each one with some click events binded (not related with this feature).

I have to add another one to each field to show a modal at first click on any of them and only at first click.

I thought something like this:

    $('.field').on('click',function(){
        $('#modal').modal();
        $('.field').off('click');
    });

The idea was that after first click, the .off() method would remove 'click handlers' from all the .field elements.

It would be great if there would not exist other cited 'click handlers', because in this way I'm removing all of them.

I'd need to remove just this specific 'click handler' from ALL fields, preserving others, in this way, the modal window should appear only on first click on any form field, and never appear again with click on next fields.

Please, how to do?

Upvotes: 0

Views: 24

Answers (1)

Jamiec
Jamiec

Reputation: 136249

Make a function which removes itself from the handlers after being called

function showModalOnlyOnce(){
  console.log("Show modal") ;
  $('.field').off('click',showModalOnlyOnce);
}

And assign this using on

$('.field').on('click',showModalOnlyOnce);

This does not affect other click handlers as the snippet below demonstrates. The "Ive been clicked" message is always written, but the "Show modal" message only ever shows up once

function showModalOnlyOnce(){
  console.log("Show modal") ;
  $('.field').off('click',showModalOnlyOnce);
}


$('.field').on('click',function(){
    console.log("Ive been clicked");   
});

$('.field').on('click',showModalOnlyOnce);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="field">
<input type="text" class="field">
<input type="text" class="field">
<input type="text" class="field">

Upvotes: 2

Related Questions