Prevent the event from being triggered 2 times

Asked

Viewed 661 times

0

When I ask to open a modal for the first time it does the actions correctly, but when I close and open again the modal it performs the function twice, as I avoid this?

inserir a descrição da imagem aqui

function acoesModal(){
    $('div#fixa').css('z-index', '0');
    $('.back-captcha').slideDown(500);
    $('.captcha').fadeIn(500);

    $('body').on('click','.captcha .fechar,.captcha button#retorno',function(event) {
            event.preventDefault();             
            $('div#fixa').removeAttr('style');
            $('.back-captcha').slideUp(500);
            $('.captcha').fadeOut(300);
            $('.captcha form textarea').val('');
        });

1 answer

1

There are two ways.

Using the function one.

$('body').one('click', function() {
    console.log('Esta função será executada apenas uma vez');
});

Using the off.

// removo todos os eventos do body com o namespace
// .fecharModal antes de adicioná-los novamente
$('body').off('.fecharModal').on('click.fecharModal', function() {
    console.log('Esta função será executada apenas uma vez');
});

The first way works well in cases where the event will happen only once. The second can be used in cases where the event can occur several times.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.