CheckboxLists.js

From The Al`Kabor Project Wiki
Revision as of 18:16, 2 December 2019 by Choir (talk | contribs) (testing from p99)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

/**

* Set the visible "checked" state of the list items when the page loads
*/

var initializeCheckboxes = function() {

 var $checkboxLis = $('.checkbox-list li');
 var status = getStateByPage('checkbox-status') || {};
 Object.keys(status).forEach(function(key) {
   if (!status[key]) return;
   var index = parseInt(key);
   if (index < 0) return; // A bogus index got set; ignore it
   $checkboxLis.eq(index).addClass('checked');
 });

};

/** Attach click handlers to the spans we added */ var listenForSpanClicks = function() {

 $('.checkbox-list li span').click(function(e) {

e.stopPropagation(); // for

  • s nested in other <lis> const $li = $(e.target).parent(); toggleIsChecked($li); }); }; /** * Both changes the DOM to make the item appear visibly checked, and updates * the "checked" status in local storage */ var toggleIsChecked = function($li) { var isChecked = !$li.is('.checked'); // Clicks toggle checked status $li.toggleClass('checked', isChecked); setCheckedStatus($li, isChecked); }; /** * Attach click handlers to the lis also, but only use them if the click was * on the left (checkbox) part */ var listenForLiClicks = function() { $('.checkbox-list li').click(function(e) { e.stopPropagation(); // for
  • s nested in other <lis> if (e.offsetX > 50) return var $target = $(e.target); toggleIsChecked($target); }); }; var wrapContentsInSpan = function($li) { return '' + $li.html() + ''; }; /** * Wrap the contents of all checbox LIs in a span so that clicks only work * on the text, not on the LI's entire (ie. page) width */ var addWrappingSpans = function() { $('.checkbox-list li') .map(function(i, li) { return $(li); }) .each(function(i, $li) { $li.html(wrapContentsInSpan($li)); }) }; /** * Sets the status, in local storge, of the checkbox specified by the * provided index, to the providd "isChecked" boolean */ var setCheckedStatus = function($li, isChecked) { var index = $('.checkbox-list li').index($li); if (index < 0) return; // Don't set index -1, it means something went wrong var status = getStateByPage('checkbox-status') || {}; status[index] = isChecked; setStateByPage('checkbox-status', status); }; var setupCheckboxes = function() { addWrappingSpans(); listenForSpanClicks(); listenForLiClicks(); initializeCheckboxes(); }; setupCheckboxes();