Change the color of a table cell with the current color recorded in localstorage
Task: there is a table of several cells (for example - 4). Each cell has the same background color (for example, red). It is necessary that when you click on a cell, the color changes to another one (for example, green), and the color data for each cell is stored in localstorage, so that after updating/reopening the page, the table remembers its state.
0
Author: aleksandr barakin, 2020-01-11
1 answers
For ordered cells
const COLOR_1 = 'red';
const COLOR_2 = 'green';
const init = () => {
// получаем массив с классами из localStorage
const data = JSON.parse(localStorage.getItem('classes'));
// эта проверка нужна, что бы сделать красным цветом ячейки, индексов которых нет в localStorage
// т.е, если в localStorage данные для 4 ячеек а мы в разметку добавили ещё 4
if (data.length < tds.length)
// возвращаем новый массив, который состоит из массива data и нового массива, длинна которого равна недостающему количеству элементов
// функция createArray расположена ниже
// https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Spread_syntax
return [...data, ...createArray(tds.length - data.length)]
else if (!data)
return new Array(len).fill(COLOR_1)
return data
}
// просто заполняем новый массив строками 'red' len-раз
const createArray = len => new Array(len).fill(COLOR_1)
// если элемент, по которому произошел клик, является ячейкой, меняем его цвет на зеленый
const changeColor = e => e.target.tagName == 'TD' ? e.target.classList.toggle(COLOR_2) : null
const setLocalStorage = () => {
// получаем классы для каждой ячейки и записываем их в массив
classes = [...tds].map(td => td.className)
// запихиваем этот массив в localStorage
localStorage.setItem('classes', JSON.stringify(classes))
}
const tds = document.querySelectorAll('td')
let classes = init();
// цвета для ячеек при загрузке страницы
tds.forEach((td, i) => td.className = classes[i])
const table = document.querySelector('table')
table.addEventListener('click', e => {
changeColor(e)
setLocalStorage()
})
.red {
background-color: red;
}
.green {
background-color: green;
}
<table border="1" width="100%" cellpadding="5">
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>