javascript - How to remember current toggle state in this example after page refresh with local storage? -
i have 3 tabs: 'monday', 'tuesday' , 'favorites'. each tab contains boxes empty heart @ start ('.favorite i'). want save current toggle class after refresh.
toggle:
heartlink.find('i').toggleclass('fa-heart-o fa-heart'); // .selected or not
i've started with:
if (heartlink.find('i').hasclass('fa-heart-o')) { localstorage.setitem('displayicon', 0); } else { localstorage.setitem('displayicon', 1); }
and know need similar don't know how it..
to make clear: want save current state of each specific heart. don't 1 icon affect boxes.
var showicontoggle = localstorage.getitem('displayicon'); if (showicontoggle == 'true') { // code }
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"> <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"> <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:
$('div.tab-pane').on('click', '.favorite', function(e) { e.preventdefault(); var heartlink = $(this); //toggle font awesome on click heartlink.find('i').toggleclass('fa-heart-o fa-heart'); // .selected or not, need 2 classes toggle. if (heartlink.find('i').hasclass('fa-heart-o')) { localstorage.setitem('displayicon', 0); } else { localstorage.setitem('displayicon', 1); } }); var showicontoggle = localstorage.getitem('displayicon'); if (showicontoggle == 'true') { // code here }
this question folowing that one.
to save not cloned element states (favorited or not), add this:
at end of click
handler, save classes clicked i
.
// save current toggle state localstorage.setitem(box.attr("id"), $(this).find("i").attr("class")); console.log($(this).find("i").attr("class"));
on page load, before loading favorites localstorage, apply saved classes:
// 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")) ); } });
Comments
Post a Comment