Reputation: 25
I'm not finding any answers around here that seem to address my problem. I have this function I wrote:
$(function() {
$('.js-blog-select').on('click', function() {
$(this).closest('.customize-card-md').toggleClass('bg-gray');
window.localStorage.setItem('togglebg' + this.dataset.id, $(this).closest('.customize-card-md').hasClass('bg-gray'));
});
$('.js-blog-select').each(function() {
//set unique id
var id = 'togglebg' + this.dataset.id;
if (localStorage.getItem(id) && localStorage.getItem(id) == "false") {
$(this).closest('.customize-card-md').removeClass('bg-gray');
}
});
});
Here's the simplified HTML for this (there's multiple divs on the page with class 'bg-gray' and the value of id on input is set to increment for each new div ):
<div class="done-cancel">
<input class="mba-done js-mba-done" type="submit" value="Done">
<input class="mba-cancel" type="button" />
</div>
....
<div class="customize-card-md bg-gray">
<input id="blog-1" class="customize-select" type="checkbox">
<label class="js-blog-select"></label>
</div>
The function above works just fine, toggling the class bg-gray. The issue is that I need to set the toggled state of each div only when the user clicks on Done button (.js-mba-done). I tried nesting a click event inside the first part of my onlick function, but that seemed like a bad idea. Is there a way I can set 'togglebg' only upon click of this done button?
Upvotes: 1
Views: 1297
Reputation: 30883
Please review the following example.
https://jsfiddle.net/Twisty/rwp3zq1d/
JavaScript
$(function() {
function getData(i) {
console.log("GET", i);
return JSON.parse(localStorage.getItem(i));
}
function saveData(i, v) {
console.log("SAVE", i, v);
localStorage.setItem(i, JSON.stringify(v));
}
function init() {
$(".customize-card-md").each(function(i, el) {
var i = $("input", el).attr("id").slice(-1);
if (getData("togglebg-" + i)) {
$("input", el).prop("checked", true);
$(el).removeClass("bg-gray");
}
});
}
init();
$(".customize-card-md").on("click", ".js-blog-select", function() {
var self = $(this);
var chk = self.prev("input");
var par = self.parent();
var i = chk.attr("id").slice(-1);
chk.prop("checked", !chk.prop("checked"));
if (chk.is(":checked")) {
saveData("togglebg-" + i, true);
par.removeClass("bg-gray");
} else {
saveData("togglebg-" + i, false);
par.addClass("bg-gray");
}
});
});
We can make use of Functions to do specific tasks over and over again. LocalStorage can only hold String data. You're only using True / False, but if you needed, you can store more complex data in the way shown above. For example, you could have one index, togglebgs
, and then store an Array of all the status or an Object.
If all the items are "off" when the page loads, we only have to toggle the ones that should be "on". So in out Init, we check the local storage and turn those on.
We then do the same thing with the Click delegation. With .on()
it's best to select the parent and then delegate to the child element.
Upvotes: 1