webworker
webworker

Reputation: 357

clone div into the DOM once

I have the following code;

$('[class*="time-span"]').on('click', function () {
    var modelPanel = $('.model-detail-panel');
    modelPanel.clone().insertAfter('.timeline', this).slideToggle('fast', function () {
        console.log(this);
        $('html,body').animate({
            scrollTop: $(this).offset().top
        }, 500);
    });
});

The clone part works well, however I only want 'modelPanel' to appear once in the DOM (each time [class*="time-span"] is clicked). At the moment It's being inserted multiple times after every 'timeline' class, resulting in quite a few instances of the div being inserted.

How can I get this to insert only once per click?

Thanks

Upvotes: 1

Views: 556

Answers (4)

StaticVariable
StaticVariable

Reputation: 5283

You can do this by removing the class.If class will removed than click event will not work or this will instered once only

$('[class*="time-span"]').on('click', function () {
    var modelPanel = $('.model-detail-panel');
    modelPanel.clone().insertAfter('.timeline', this).slideToggle('fast', function () {
        console.log(this);
        $('html,body').animate({
            scrollTop: $(this).offset().top
        }, 500);

 $(this).removeClass("time-span");
    });
});

Upvotes: 0

David Hoerster
David Hoerster

Reputation: 28711

Use the :first selector:

$('[class*="time-span"]').on('click', function () {
    var modelPanel = $('.model-detail-panel');
    modelPanel.clone().insertAfter('.timeline:first', this).slideToggle('fast', function () {
        console.log(this);
        $('html,body').animate({
            scrollTop: $(this).offset().top
        }, 500);
    });
});

Upvotes: 1

BadHorsie
BadHorsie

Reputation: 14564

You probably need to be more specific than inserting after .timeline because jQuery will perform the insertAfter on every element with a class of .timeline that it finds on your page.

Try using a selector that is only found in one place.

Upvotes: 0

yodog
yodog

Reputation: 6252

probably because you are cloning based on a .class.

you can have several elements with the class .model-detail-panel, so you're cloning all of them, not just one.

try cloning based on other attribute.

Upvotes: 0

Related Questions