Search code examples
javascriptjqueryclonestore

How to save each cloned div into localstorage with a different key/value


Here's a sample of my code:

<!doctype html>
  <html>
    <head>
        <meta charset="UTF-8">
        <title>Untitled Document</title>
    </head>

    <body>
      <div class="box not-selected" id="box1">
        <a href="#" id="clone_once1" class="favorite"></a>
      </div>
      <div class="box not-selected" id="box2">
        <a href="#" id="clone_once2" class="favorite"></a>
      </div>
      <div class="box" id="fav"></div>

      <script>

        $('#clone_once1').on('click', function(){

          // Clone div
          var add = $(this).parent();
          add.each(function(){
            var boxContent = ($(this).clone(true).addClass('selected').removeClass('not-selected'));
            var get = $('#fav').append($(boxContent)).html();

            localStorage.setItem('clicked1', get);

            // Append item if localstorage is detected = Box1 Clone
            if (localStorage["clicked1"]) {
              $("#fav").append(localStorage["clicked1"]);
            };
          });
        });

        $('#clone_once2').on('click', function(){
          var add_2 = $(this).parent();
          add_2.each(function(){
            var boxContent_2 = ($(this).clone(true).addClass('selected').removeClass('not-selected'));
            var get_2 = $('#fav').append($(boxContent_2)).html();

            localStorage.setItem('clicked2', get_2);

            // Append item if localstorage is detected = Box2 Clone
            if (localStorage["clicked2"]) {
              $("#fav").append(localStorage["clicked2"]);
            };
          });
        });

      </script>
   </body>
</html>

Let's say I click in the a tag within the #box1 and then in the #box2.

The first value is picked right (#box1.html), however when I click on the second one it picks the html of the previous div clicked and then adds the new one (#box1.html, #box2.html). So in the end, when I refresh the page I get 3 divs, which is something I don't want to see. I need only these two divs to show.

How to prevent from this to happen?

I'm quite new to js and I would appreciate any help on this matter.


Solution

  • You are facing issue because you are appending content to #fav and then putting those in local storage, In below code on every click i have made #fav empty, So now every time you add anything old content will get removed.

       $('#clone_once1').on('click', function(){
    
          // Clone div
         // var objTemp = $('#fav').html("");//change
          var add = $(this).parent();
          add.each(function(){
            var boxContent = ($(this).clone(true).addClass('selected').removeClass('not-selected'));
    
            //var get = $('#fav').append($(boxContent)).html();
            var get = $(boxContent).html().trim();
            //if(localStorage.getItem('clicked1').length)
            var temp = localStorage.getItem('clicked1');
            if(temp==null)
            {
                var tempArray = [];
                tempArray[0] = get;
                localStorage.setItem('clicked1', JSON.stringify(tempArray));
            }else{
                var tempArray = JSON.parse(temp);
                tempArray.push(get);                
                localStorage.setItem('clicked1', JSON.stringify(tempArray));
            }
    
            // Append item if localstorage is detected = Box1 Clone
            if (localStorage["clicked1"]) {
                var tempHtml = "";
                $.each(JSON.parse(localStorage["clicked1"]),function(i){
                    tempHtml += '<div class="box not-selected" id="box2">'+JSON.parse(localStorage["clicked1"])[i]+'</div>';
                }
                );
                //$("#fav").html("");
                $("#fav").append(tempHtml);
            };
          });
        });
    
        $("#clone_once2").on('click', function(){
        //$('#fav').html("");//change
          var add_2 = $(this).parent();
          add_2.each(function(){
            var boxContent_2 = ($(this).clone(true).addClass('selected').removeClass('not-selected'));
    
            //var get_2 = $('#fav').append($(boxContent_2)).html();
            var get_2 = $(boxContent_2).html().trim();
            //localStorage.setItem('clicked2', get_2);
            var temp = localStorage.getItem('clicked2');
            if(temp==null)
            {
                var tempArray = [];
                tempArray[0] = get_2;
                localStorage.setItem('clicked2', JSON.stringify(tempArray));
            }else{
                var tempArray = JSON.parse(temp);
                tempArray.push(get_2);              
                 localStorage.setItem('clicked2', JSON.stringify(tempArray));
            }
    
            // Append item if localstorage is detected = Box2 Clone
            if (localStorage["clicked2"]) {
                var tempHtml = "";
                $.each(JSON.parse(localStorage["clicked2"]),function(i){
                    tempHtml += '<div class="box not-selected" id="box2">'+JSON.parse(localStorage["clicked2"])[i]+'</div>';
                }
                );
            //$("#fav").html("");
            $("#fav").append(tempHtml);
            };
          });
        });