I am attempting to create a modal window with jquery and seem to have done it fairly well. The only problem is when I click the contact button for the second time it seems to append two modal boxes. One on top of the other. And a third if clicked again....

Here is the code:

$('#contact').on( 'click', function(e){
        e.preventDefault();
        $('body').append('<div id="modal"></div>');
        $("#modal").load('/forms/contact-form.html').hide().fadeIn(1000);
    });

    $('#send').click(function(e){
        $('#modal').remove();
    });

Can someone please explain why this is happening? Also any feedback about what I am attempting here is welcome.

有帮助吗?

解决方案

Best way is to remove modal div when you are creating new modal div.

$('#contact').on('click', function () {
    $('#modal').remove(); //remove modal here
    $('body').append('<div id="modal"></div>');
    $("#modal").load('/forms/contact-form.html').hide().fadeIn(1000);
});

其他提示

Try removing,before appneding.

$('#contact').on( 'click', function(e){
        e.preventDefault();
        $('#modal').remove();
        $('body').append('<div id="modal"></div>');
        $("#modal").load('/forms/contact-form.html').hide().fadeIn(1000);
    });

After click, you should delete some modal boxes, that are showing on the page in that time. Sure, if some exists.

$('body').find("#modal").remove();

Or just short form:

$("#modal").remove();

At the time of #send click #modal is not removed because it is created dynamically, so try it by using on()

$(document).on('click','#send',function(e){// jquery event delegation
    $('#modal').remove();// it will remove the dynamically created modal box
});

Alternatively you can use the code like,

$('#contact').on( 'click', function(e){
    e.preventDefault();
    if(!$('#modal').length)// append modal only if not present
       $('body').append('<div id="modal"></div>');
    $("#modal").load('/forms/contact-form.html').hide().fadeIn(1000);
});

Why

Your code is appending a new div each time the #contact element is clicked. Therefore each time the button is clicked the browser is rendering a new modal window.

Solution

Create the modal div only once and reuse it as a variable. You can do this using the .appendTo() method.

Here's a demo

var $modal = false;

$('#contact').on( 'click', function(e){

    e.preventDefault();

    if ( ! $modal ){

      $modal = $('<div id="modal"></div>').appendTo('body');

    }

    $modal.load('/forms/contact-form.html').hide().fadeIn(1000);

});

$('#send').click(function(e){

    if ( $modal )
      $modal.hide();

});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top