Home > Net >  how to add close button in Appended Items?
how to add close button in Appended Items?

Time:10-14

I work on a project where I use the Localstorage function along with clone and it works fine

but the problem how to add number increment in .count class like I click on save1 save2 save3 then total number count shown like <div class='count'>3</div>

Here is Demo of my code DEMO of Close Buttons I tried to create

Any kind of help or suggestions is highly appreciated

CodePudding user response:

If you check you can create a function and there create a div element and append the cloned item and append a close button created from the code, then you can reuse that function to create elements from any method, you just need to pass the selected object and in the "close" method you can use the function "parent" to select the "div" parent element and get the attribute id from there, like the code below.

function createItem(item){
    var elemId = item.data("id");
    var clonedItem = item.clone();
    var newItem = $(`<div data-id="${elemId}"></div>`);
    newItem.append(clonedItem);
    newItem.append(`<button class='close'>Close</button>`)
    newItem.appendTo('.item-append');
}

function countSaveItems(){
    $('.count').html($(".item-append div.item-save[data-id]").length);
}


$('.item-all .item-save').click(function() {
  $(this).toggleClass('productad')
  window.localStorage.setItem('test_'   this.dataset.id, $(this).hasClass('productad'));
});
$('.item-all .item-save').each(function() {
  var id = 'test_'   $(this).data("id"); //
  if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
    $(this).addClass('productad');
    createItem($(this));
    countSaveItems();
  }
});
$(".item-all .item-save").click(function() {
  var elemId = $(this).data("id");
  var existing = $(`.item-append div[data-id="${elemId}"]`);
  if (existing.length > 0){
    existing.remove();
  }else{
    createItem($(this));
  }
  countSaveItems();
});

$(".item-append").on("click", ".close", function() {
    var id = $(this).parent().data("id");
    localStorage.removeItem(`test_${id}`);
  $(`.item-save[data-id='${id}']`).removeClass('productad');
    $(this).parent().remove();
  countSaveItems();
  
} );
.item-save {
    position: relative;
    display: block;
    font-size: 14px;
    width:80px;
    margin: 5px;
    padding: 5px;
    background: #a5a5a5;
    text-align: center;
    cursor: pointer;
}
.item-all{display:flex}
.productad{background:red;color:#eee}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item-all'>
<div class='item-save' data-id='123'>
Save1
</div>
<div class='item-save' data-id='124'>
Save2
</div>
<div class='item-save' data-id='125'>
Save3
</div>
<div class='item-save' data-id='126'>
save4
</div>
</div>
<hr/>
<div class='item-append'>
</div>

  • Related