I am trying to clone elements onclick one time only but multiple items are being cloned when I click continuously multiple times then multiple items created.
I don't understand why multiple items are created continuously. I only want items from the data-id should be appended one time even if I click it should be removed the cloned item. Also when we click appended items they should be removed.
$('.item-save').click(function() {
$(this).toggleClass('productad')
window.localStorage.setItem('test' + this.dataset.id, $(this).hasClass('productad'));
});
$('.item-save').each(function() {
var id = 'test' + this.dataset.id;
if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
$(this).addClass('productad');
}
});
$('.item-save').click(function() {
var id = this.dataset.id;
$(".item-save").attr("data-id", function() {
var $button = $(this).clone();
$button.appendTo('.item-append');
});
});
.item-save {
position: relative;
display: block;
font-size: 14px;
margin: 5px;
padding: 5px;
background: #a5a5a5;
text-align: center;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class='item-all'>
<div class='item-save' data-id='123'>Save</div>
<div class='item-save' data-id='124'>Save</div>
<div class='item-save' data-id='125'>Save</div>
<div class='item-save' data-id='126'></div>
</div>
<div class='item-append'></div>
Here is my code JsFiddle Demo
I work with localStorage function to store some value so that is important without removing localStorage is it possible to fix this issue Any help or advice is highly appropriated
Get rid of the attr() function in your second click function.
Change this
$('.item-save').click(function() {
var id = this.dataset.id;
$(".item-save").attr("data-id", function() {
var $button = $(this).clone();
$button.appendTo('.item-append');
});
});
To this
$('.item-save').click(function() {
var $button = $(this).clone();
$button.appendTo('.item-append');
});