Question

I have this snippet of code that adds a new div to my page.

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

        $('.layer').removeClass('selectedLayer');
        var nl = $('<div class="layer selectedLayer" data-arc="1100">New Layer</div>').insertAfter('.layer');
        nl.arctext({radius: 1100});
        nl.resizable({handles: "nw,sw,se,ne"}).draggable().rotatable({ handles: "s"});
        $('#bead-text').val('New Layer');

    });

The first time it is called it works perfect. The second time instead of adding just one div it adds 2 with 1 click. The third time I click it it adds 4 with 1 click. Any idea how I can fix this so it just adds one at a time?

Was it helpful?

Solution

That is because your selector .layer returns multiple elements after your first addition and hence it will add one for each of them, So use .layer:last

Try:

$('<div class="layer selectedLayer" data-arc="1100">New Layer</div>').insertAfter('.layer:last');

Demo

OTHER TIPS

Well, now have two .layers after the first click. So, when you do

$('<div class="layer selectedLayer" data-arc="1100">New Layer</div>').insertAfter('.layer');

You are inserting that element per .layer.

I would recommend first to target the element and then add after it like this:

var html = '<div class="layer selectedLayer" data-arc="1100">New Layer</div>';

// select the last element with .layer and put HTML after it
var nl = $('.layer').last().after(html);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top