fade-out transition on bgcolor not working

53 views Asked by At

So I have a button that scrolls to a specific div and highlights it yellow for a second, but I can't make it fade out instead of just dissapearing. This is my code:

function Go_to_file_creator() {
  var divElement = document.getElementsByClassName('form')[0];
  divElement.scrollIntoView();
  divElement.classList.add('highlighted');

  setTimeout(function() {
    divElement.classList.remove('highlighted');
  }, 1000);
}
#toFileCreator {
  margin-right: 90vw;
  z-index: 999;
  margin-bottom: 20px;
  margin-left: 20px;
}

.highlighted {
  background-color: yellow;
  transition: background-color 1s;
}
<button onclick="Go_to_file_creator()" id="toFileCreator">
  <h1>File creator</h1>
</button>

Any help would be appreciated.

1

There are 1 answers

1
Yogi On BEST ANSWER

To make your code fade-in and fade-out, you need to have a forward and reverse transition. The original code only has a forward transition. So the background color change is instantaneous when you remove the class.

Add this line to your css:

.form {
  transition: background-color 3s;
}

Run the snippet to understand how it works.

Snippet

function Go_to_file_creator() {
  var divElement = document.getElementsByClassName('form')[0];
  divElement.scrollIntoView();
  divElement.classList.add('highlighted');

  setTimeout(function() {
    divElement.classList.remove('highlighted');
  }, 1000);
}
#toFileCreator {
  margin-right: 90vw;
  z-index: 999;
  margin-bottom: 20px;
  margin-left: 20px;
}

.form {
  transition: background-color 3s;
}

.form.highlighted {
  background-color: yellow;
  transition: background-color 1s;
}
<div class="form">
  <button onclick="Go_to_file_creator()" id="toFileCreator">
    <h1>File creator</h1>
  </button>
</div>