user7583090
user7583090

Reputation:

jQuery clone creating multiple of same div

I have the following code that works almost perfectly, but it's cloning the same div multiple times.

Unfortunately, once you select it and deselect it once, it starts showing multiples if you select any others. I'm assuming this has something to do with the cloning.

function selectGameItem() {

    $('.inventory-item').on('change', function() {

        var cloneDiv = $(this).clone();

        if($(this).parent('.game-inventory').length) {

            $('.receive-window').append(cloneDiv);
            $(this).addClass('selected-item');

        } else {

            $(this).remove();
            $('.game-label-' + inventoryValue).removeClass('selected-item');

        }

        selectGameItem();

    });

    }

}

Upvotes: 1

Views: 127

Answers (1)

nnnnnn
nnnnnn

Reputation: 150030

Remove the call to selectGameItem(); that is the last line of your change handler. It will call .on('change') for elements that already have handlers, so next time the event occurs duplicate handlers will run, then when they run they call selectGameItem() again and bind more handlers, etc.

If you had that line there in order to bind the change handler to the cloned items, you don't need that. You can use .clone(true) to clone the event handlers too. Or, probably better, just use a delegated event handler by changing this line:

$('.inventory-item-hold').on('change', function() {

to:

$(document).on('change', '.inventory-item-hold', function() {

That will automatically work with any elements that are added dynamically that have the '.inventory-item-hold' class. (Ideally you wouldn't use document, you'd use whatever the nearest common ancestor element is for all of the '.inventory-item-hold' elements.)

Upvotes: 1

Related Questions