AlexG
AlexG

Reputation: 5919

Remove element created with jQuery

I want to remove and add a overlay as often as I want but I cant seem to get js to remove a by js created element, any ideas?

JS Fiddle Example

html

<div id="background"></div>
<button id="open">Open</button>
<div id="overlay">
    <button id="close">Close</button>
</div>

js/jQuery

$(function() {

    $('#open').click(function() {

        $('body').append('<div id="overlay"><button id="Close">Close</button></div>');

    });

    $('#close').click(function(){
        $('#overlay').remove();
    });
});

css:

#overlay{
    padding: 8px;
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.1);
}

Upvotes: 0

Views: 132

Answers (2)

IAfanasov
IAfanasov

Reputation: 4993

You need to attach handler to click event of $('#close') once again after you add it to document.

$(function() {

    $('#open').click(function() {

        $('body').append('<div id="overlay"><button id="close">Close</button></div>');

         $('#close').click(function(){
             $('#overlay').remove();
         });

    });

    $('#close').click(function(){
        $('#overlay').remove();
    });
});

After click on close you no longer have close button with your handler attached. It deleted by $('#overlay').remove() code. After you click open button brand new #overlay element added. It isn't contains handlers for old element.

You can archive your goal with even less code:

https://jsfiddle.net/IAfanasov/msro2hoq/6/

$(function() {

    $('#open').click(function() {
        $('#overlay').show();
    });

    $('#close').click(function(){
        $('#overlay').hide();
    });
});

Upvotes: 2

Cat
Cat

Reputation: 56

Why not just show and hide it?

$(function() {

    $('#open').click(function() {

        $('#overlay').show();

    });

    $('#close').click(function(){
        $('#overlay').hide();
    });

});

Upvotes: 0

Related Questions