I have confirmed that localstorage is storing the row id with
sessionStorage.setItem(rowId, 'true');
I am trying to re-apply the css .selected class name back to the row id when the page is refreshed with
Main purpose is to keep the selected row highlighted when page is reloaded
if (localStorage.getItem('1') === 'true' || localStorage.getItem('2') === 'true') {
}
.selected {
box-shadow: inset 0px 0px 10px #FF0000;
border: 2px solid rgba(255,255,255,.5);
}
-- Java function that highlights the table row when clicked and stores the row id with sessionStorage.setItem(rowId, 'true');
<script type="text/javascript">
highlight_row();
function highlight_row() {
var table = document.getElementById('display-table');
var cells = table.getElementsByTagName('td');
for (var i = 0; i < cells.length; i ) {
// Take each cell
var cell = cells[i];
// do something on onclick event for cell
cell.onclick = function () {
// Get the row id where the cell exists
var rowId = this.parentNode.rowIndex;
var rowsNotSelected = table.getElementsByTagName('tr');
for (var row = 0; row < rowsNotSelected.length; row ) {
rowsNotSelected[row].style.backgroundColor = "";
rowsNotSelected[row].classList.remove('selected');
}
var rowSelected = table.getElementsByTagName('tr')[rowId];
rowSelected.style.backgroundColor = "yellow";
rowSelected.className = " selected";
sessionStorage.setItem(rowId, 'true');
//alert(rowId);
}
}
}
</script>
CodePudding user response:
I recommend to replace this line
// that would add multiple entries per click on different rows
// eg: 1: true, 3: true, 47: true
sessionStorage.setItem(rowId, "true");
with
sessionStorage.setItem('rowId', rowId);
That will overwrite the value for last clicked rowId and you don't have to check for all possible rows / key value pairs.
To set the classes use the code you already wrote in your click handler. Put that block after your for loop.
// your for loop
for (var i = 0; i < cells.length; i ) {
...
}
// new code
// check if rowId key exist
// if rowId does not exist null is returned - so we can check for that
if ( sessionStorage.getItem('rowId') !== null ) {
rowSelected = table.getElementsByTagName('tr')[sessionStorage.getItem('rowId')];
rowSelected.style.backgroundColor = "yellow";
rowSelected.className = " selected";
}