Removing class after adding it in Switch Case Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Removing class after adding it in Switch Case without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Can I remove the jumping class without having to call another function to remove it?
I would like the function to change the styling and then remove the class because the key up event interupts others styling changes in the code. Is Set Interval appropriate to use here?

document.addEventListener('keydown', jump);
document.addEventListener('keyup', landing);

function jump(e) {
  switch (e.keyCode) {
    case 32:
      if (!spritejump.classList.contains('jumping'))
        spritejump.classList.add('jumping');
      break;
  }
}

function landing(e) {
  switch (e.keyCode) {
    case 32:
      if (spritejump.classList.contains('jumping'))
        spritejump.classList.remove('jumping');
      break;
  }
}

Answer

If you know how long your (e.g.) animation is, you could use setTimeout.

document.addEventListener('keydown', (e) => {
  switch (e.keyCode) {
    case 32:
      // add the jumping class
      spritejump.classList.add('jumping');

      // remove the jumping class after 2 seconds
      setTimeout(() => {
        spritejump.classList.remove('jumping');
      }, 2000);
      break;
  }
});
We are here to answer your question about Removing class after adding it in Switch Case - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji