webworker
webworker

Reputation: 357

Append div into dynamically created div

I have the following code (lifted from CSS-Tricks) and want to add another div (modal window) into it, but I cant seem to get this to work. The stock-modal div already exists in the DOM, but is currently hidden as I only want it to appear when the #overlay div is present;

$('.stock-check').on('click', function () {

    var docHeight = $(document).height();

    $('body').append('<div id="overlay" />');
    $('#overlay').height(docHeight).css({
        'opacity': 0.7,
        'position': 'absolute',
        'top': 0,
        'left': 0,
        'background-color': 'black',
        'width': '100%',
        'z-index': 10000
    });

    $('<div class="stock-modal" />').appendTo('#overlay').show();

});

When this runs, it inserts an empty stock-modal div inside the overlay div but not the one that exists in the DOM. What am I doing wrong?

Upvotes: 1

Views: 1469

Answers (3)

kidz
kidz

Reputation: 308

Check Whether the overlay div already exists, then just adds the modal otherwise create the overlay and add the modal.

$('.stock-check').on('click', function () {

 var docHeight = $(document).height();

if($('#overlay').length > 0)
{
  $('<div class="stock-modal" />').appendTo('#overlay').show();
}
else
{
 $('body').append('<div id="overlay" />');
 $('#overlay').height(docHeight).css({
    'opacity': 0.7,
    'position': 'absolute',
    'top': 0,
    'left': 0,
    'background-color': 'black',
    'width': '100%',
    'z-index': 10000
 });

 $('<div class="stock-modal" />').appendTo('#overlay').show();
}

});

Upvotes: 0

Yograj Gupta
Yograj Gupta

Reputation: 9869

You should change to, first select the existing .stock-modal div and appendTo #overlay

$('.stock-modal').appendTo('#overlay').show();

Upvotes: 1

Pulkit Goyal
Pulkit Goyal

Reputation: 5654

Don't create a new div. Append existing one by selecting it first.

$(".stock-modal").appendTo('#overlay').show();

Upvotes: 2

Related Questions