javascript - Why is persisting data not working as it should? -


i'm working 3 tabs called 'monday', 'tuesday' , 'favorites'. have toggle icon empty heart @ start 'favorite i'. if i'm in monday , click on icon, empty heart turns filled out , parent cloned , added '#fav' tab. when happens clone saved local storage. if people refresh page, can still see preferences.

when heart clicked in 1 of cloned divs specific div removed '#fav' , removed array.

everything works well, except when refresh browser , local storage detected.

so, in case if i'm in monday , click on filled heart doesn't remove clone #fav , still adds new clone #fav. also, if i'm in #fav tab, when clicking in 1 of hearts, should erase index array, in fact, erases full array.

how overcome issue? many thanks.

html:

<section id="speakers-programme">   <div class="container">     <div class="tabs_main">        <div class="col-md-5"><a data-target="#mon" class="btn active" data-toggle="tab">monday</a></div>       <div class="col-md-5"><a data-target="#tue" class="btn active" data-toggle="tab">tuesday</a></div>       <div class="col-md-2"><a data-target="#fav" class="btn active" data-toggle="tab"><i class="fa fa-heart" aria-hidden="true"></i></a></div>      </div>      <div class="tab-content">       <div class="tab-pane active" id="mon">         <br>         <div class="spaces">           <div class="box-container">             <div class="box not-selected" id="box1">               <span>1</span>               <a href="#" class="favorite"><i class="fa fa-heart-o" aria-hidden="true"></i></a>             </div>           </div>           <div class="box-container">             <div class="box not-selected" id="box2">               <span>2</span>               <a href="#" class="favorite"><i class="fa fa-heart-o" aria-hidden="true"></i></a>             </div>           </div>         </div>       </div>        <div class="tab-pane active" id="tue">         <br>         <div class="spaces">         </div>       </div>        <div class="tab-pane active" id="fav">         <br>         <div class="spaces">         </div>       </div>      </div>   </div> </section> 

js

console.clear(); //localstorage.setitem('sessions', "");  var temparray = [];  // clones $('div.tab-pane').on('click', '.favorite', function(e) {   e.preventdefault();    // elements play with... having significative variable names.   var heartlink = $(this);   var box = heartlink.parent('.box');   var container = box.parent('.box-container');   var favoritetab = $("#fav .spaces");    // don't know use 3 lines below.   var idfind = box.attr("id");   var idcomplete = ('#' + idfind);   console.log(idcomplete);    //toggle font awesome on click   heartlink.find('i').toggleclass('fa-heart fa-heart-o'); // .selected or not, need 2 classes toggle.   box.toggleclass("selected not-selected"); // toggle selected , not-selected classes    // clone div   var boxcontent = container.clone(true, true);    // change id   var thisid = boxcontent.attr("id")+"_cloned";   boxcontent.attr("id", thisid);    // html saved in localstorage   var = boxcontent.wrap('<p>').parent().html();   = get.replace(/\r?\n/g, "").replace(/>\s*</g, "><"); // remove line feeds , spaces   console.log(get);   boxcontent.unwrap();    // decide add or remove   if(box.hasclass("selected")){     console.log("add array")     temparray.push(get);      // add favorites tab     favoritetab.append(boxcontent);    }else{     console.log("remove array");     var index = temparray.indexof(get);     temparray.splice(index);      // remove favorite tab     favoritetab.find("#"+thisid).remove();   }    // save array   localstorage.setitem('sessions', temparray.join(""));   console.log(temparray);    // save current toggle state   localstorage.setitem(box.attr("id"), $(this).find("i").attr("class"));   console.log($(this).find("i").attr("class"));  });  // append item if localstorage detected if (localstorage["sessions"]) {   console.log("storage exist");    // load    $(".box").each(function(){     console.log( $(this).attr("id") );     console.log( localstorage.getitem($(this).attr("id")) );      if(localstorage.getitem($(this).attr("id")) != null){       $(this).find("i").removeclass().addclass( localstorage.getitem($(this).attr("id")) );     }   });    $("#fav .spaces").append(localstorage["sessions"]);   console.log( localstorage["sessions"] ); } 

fiddle: https://codepen.io/bes7web/pen/bobjdv?editors=1011

i twisted code in way deserves explanations.

first, don't need save html of favorited elements. need heart icon states, do. added counter, know how many favorited there in storage.

now, on page load... if there more 0 favorites in storage, apply icon states loading classes storage. had part right. then cycle throught hearts target filled ones , clone them in favorite tab. made "named function" this.

on icon click now... clicking on cloned element or on original element 2 different situations.

on original element, want toggle classes , clone favorite tab. here, togglings , favorite tab, call previous named function clone them all!

on cloned element, want remove favorites , toggle original element classes. see code twist made! redefined variables in case.

notice there no more temparray in use.
;)

var favoritetab = $("#fav .spaces");  // named function load favorites tab function loadfav(){   // first, clear old favorites.   favoritetab.empty();    // filled hearts   var favcount = 0;   $(".tab-content").find("i.fa-heart").each(function(){     // count them     favcount++;     // clone box     var favclone = $(this).closest(".box").clone();     // change id     favclone.attr("id", favclone.attr("id")+"_clone");     // append favorites     favoritetab.append(favclone);   });    console.log("favcount: "+favcount);   localstorage.setitem("favamount", favcount); }  // click handler $('div.tab-pane').on('click', '.favorite', function(e) {   e.preventdefault();    // elements play with... having significative variable names.   var heartlink = $(this);   var box = heartlink.parent('.box');   var thisid = box.attr("id");   var container = box.parent('.box-container');    if(thisid.split("_")[1] == "clone"){     console.log("you clicked clone!");     // remove clone     box.remove();     // use original element rest of function.     heartlink = $("#"+thisid.split("_")[0]).find("a.favorite");     box = heartlink.parent('.box');     thisid = box.attr("id");   }    //toggle font awesome on click   heartlink.find('i').toggleclass('fa-heart fa-heart-o'); // .selected or not, need 2 classes toggle.   box.toggleclass("selected not-selected"); // toggle selected , not-selected classes    // clone div   loadfav();    // save current toggle state   localstorage.setitem(box.attr("id"), heartlink.find("i").attr("class"));   console.log(heartlink.find("i").attr("class"));  });     // on page load // append item if localstorage detected if (localstorage["favamount"]>0) {   console.log("storage exist");    // load heart's element states   $(".box").each(function(){     console.log( $(this).attr("id") );     console.log( localstorage.getitem($(this).attr("id")) );      if(localstorage.getitem($(this).attr("id")) != null){       $(this).find("i").removeclass().addclass( localstorage.getitem($(this).attr("id")) );     }   });    // load favorites   loadfav();  }else{   console.log("no storage"); } 

codepen v6


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -