Heisenberg
Heisenberg

Reputation: 5299

How to redo classchange in html tables

I would like to redo classchange in html tables.

undomethod is realized by pop.but I doubt are there any way to redo it.

My desired result is when I clickundo,redo button, classchange will redoandoundo

Are there any useful method for redo it?

Thanks

$(function() {
  let clicked = [];
  $("td").click(function() {
    let clickedID = $(this).attr('id');
    clicked.push(clickedID);
    $(this).addClass("aqua");
  });
  $("#undo").on('click',() => {
    if(clicked.length) {
      let lastClicked = clicked.pop();
      $(`td#${lastClicked}`).removeClass("aqua");
    }
  })
});
.aqua{
  background-color: aqua;
}


td {
  padding: 5px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <td id="1">1</td>
  <td id="2">2</td>
  <td id="3">3</td>
  <td id="4">4</td>
  <td id="5">5</td>
  <td id="6">6</td>
  <td id="7">7</td>
  <td id="8">8</td>
  <td id="9">9</td>
  <td id="10">10</td>
</table>

<button id="undo">undo</button>
<button id="redo">redo</button>

Upvotes: 1

Views: 28

Answers (1)

ROOT
ROOT

Reputation: 11622

All what you have to do is to reverse the order of execution while tracking what you are doing with redo and undo buttons, I think this is what you want:

$(function() {
  let clicked = [];
  let redoClicked = [];
  $("td").click(function() {
    let clickedID = $(this).attr('id');
    clicked.push(clickedID);
    $(this).addClass("aqua");
  });
  $("#undo").on('click',() => {
    if(clicked.length) {
      let lastClicked = clicked.pop();
      redoClicked.push(lastClicked);
      $(`td#${lastClicked}`).removeClass("aqua");
    }
  })
  $("#redo").on('click',() => {
    if(redoClicked.length) {
      let lastClicked = redoClicked.pop();
      clicked.push(lastClicked);
      $(`td#${lastClicked}`).addClass("aqua");
    }
  })
});
.aqua{
  background-color: aqua;
}


td {
  padding: 5px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <td id="1">1</td>
  <td id="2">2</td>
  <td id="3">3</td>
  <td id="4">4</td>
  <td id="5">5</td>
  <td id="6">6</td>
  <td id="7">7</td>
  <td id="8">8</td>
  <td id="9">9</td>
  <td id="10">10</td>
</table>

<button id="undo">undo</button>
<button id="redo">redo</button>

Upvotes: 2

Related Questions