JQuery UI dialog - event on close issue

I am trying to perform a specific action when I close the jQuery interface dialog. Here's a simplified version of my code:

$('a.open-trigger').click(function(){
    var test = 'hello';

    $('#dialog').dialog({
        bgiframe: true,
        dialogClass: 'change', 
        resizable: false,
        draggable: false,
        modal: true,
        height: 334, 
        width: 450,
        autoOpen: false,
        show: 'fade'
    });

    $('#dialog').dialog('open');

    $('a.close-trigger').click(function(){
        alert(test);
        $('#dialog').dialog('close');
    });
});

      

The first time I close the dialog, I get the expected warning with the word "hello". If I open the dialog a second time and close it, I get a "hello" warning twice. If I open and close it a third time, I get three warnings and so on.

Why do these warnings duplicate themselves? I would like the alert to only show once on close, no matter how many times I open / close the dialog.

Thanks! Simon

+1


a source to share


3 answers


When attaching additional event handlers every time you call .click

. This is why it duplicates.

$('a.close-trigger').click(function(){
                    alert(test);
                    $('#dialog').dialog('close');
            });

      



Extract this code to the same level as binding the other event and it should work as expected.

+8


a source


You have bound a function to the open button that adds an event handler to the close button every time an open event is fired. You must add your close event handler somewhere outside of the "a.open-trigger" event function ...



$('a.open-trigger').click(function(){
        var test = 'hello';

        $('#dialog').dialog({bgiframe: true, dialogClass: 'change', resizable: false, draggable: false, modal: true, height: 334, width: 450, autoOpen: false, show: 'fade'});
        $('#dialog').dialog('open');
});

$('a.close-trigger').click(function(){
        alert(test);
        $('#dialog').dialog('close');
});

      

+1


a source


You need to take your click close event handler from your open click event handler

$(function() {
    $('#dialog').dialog({bgiframe: true, dialogClass: 'change', resizable: false, draggable: false, modal: true, height: 334, width: 450, autoOpen: false, show: 'fade'});

    $('a.open-trigger').click(function(){    
        $('#dialog').dialog('open');
    });


    $('a.close-trigger').click(function(){
        alert("hello");
        var myDialog = $('#dialog');
        if (myDialog.dialog('isOpen'))
            myDialog.dialog('close');
    });
});

      

0


a source







All Articles