Home > Software engineering >  CSS transition colors with jQuery and CSS only?
CSS transition colors with jQuery and CSS only?

Time:10-17

I see a lot of answers say to use jquery-ui animate() function, but this requires an import of an entire other library just to flip colors.

Is there a way I can stick with just jQuery and CSS only?

The problem: When I click a button, I would like another element to flash color to blue, then back to red (red is original color). Each time the user clicks the button, this color change behavior will repeat.

I have been able to get it to change colors to blue:

$(".my-button").click(function() {        
    $(".other-element").css("transition", "color .3s").css("color", "blue");
});

Is there a way I can do the same for changing the color back to red? Something simple like:

$(".my-button").click(function() {        
    $(".other-element").css("transition", "color .3s").css("color", "blue");
    $(".other-element").css("transition", "color .6s").css("color", "red");
});

... Where the element changes to blue after .3s, and then back to red after .6s? Note, the above code doesn't work, it only shows red (never changes to blue).

CodePudding user response:

I propose to do without third-party libraries at all. Here I create a css animation and with the help of a simple js code I add an animating class at the beginning, and then remove it at the end of the animation.

const button = document.querySelector('.my-button');
const other = document.body;

button.addEventListener('click', function() {
  other.classList.add('active');
});
other.addEventListener('animationend', function() {
  other.classList.remove('active');
});
body {
  margin: 0;
  background-color: #f00;
  display: flex;
  min-height: 100vh;
}

.my-button {
  margin: auto;
  background-color: white;
  border: none;
  border-radius: 3px;
  padding: 10px 20px;
  transition: .2s;
  box-shadow: 1px 1px 4px rgba(0, 0, 0, .5);
}

.my-button:hover {
  background-color: #ddd;
}

.active {
  animation: bganim .6s;
}

@keyframes bganim {
  0,
  100% {
    background-color: #f00;
  }
  50% {
    background-color: #00f;
  }
}
<button >Click me</button>

  • Related