KunLun
KunLun

Reputation: 3225

JQuery add class after another one was added and is visible

I have a button. I want to add to this button class: space and after this class was added and is visible in browser I want to add another class: spinner

I have tried with:

$("button").on("click", function(){

    $(this).addClass("space");
    $(this).addClass("spinner");
}

CSS:

.spacer{
    transition: .3s !important;
    padding-right: 3.1rem !important;
}

.spinner{
    border: 5px solid #f3f3f3;
    border-radius: 50%;
    border-top: 5px solid #3498db;
    width: 10px;
    height: 10px;
    animation: spin 2s linear infinite;
}

But it, obviously, doesn't work. Why?

Can a class be added to an element only after a class was added and has made its effect?

Upvotes: 0

Views: 242

Answers (3)

ArslanIqbal
ArslanIqbal

Reputation: 629

You can add event listener to check if the transition is completed. Consider the code below:

var el = document.getElementById('someelement');
debugger;
function transitionCallback(){
    var t;
    var transitions = {
      'transition':'transitionend',
      'OTransition':'oTransitionEnd',
      'MozTransition':'transitionend',
      'WebkitTransition':'webkitTransitionEnd'
    }
    for(t in transitions){
        if( el.style[t] !== undefined ){
            return transitions[t];
        }
    }
}

/* Listen for transition */
var transitionEvent = transitionCallback();
transitionEvent && el.addEventListener(transitionEvent, function() {
    console.log('Transition complete.');
});
/*transition example is from w3schools*/
#someelement {
  width: 100px;
  height: 100px;
  background: red;
  transition: width 2s;
  -webkit-transition: width 2s; /* Safari 3.1 to 6.0 */
}

#someelement:hover {
  width: 300px;
}
<html>
  <head>
  </head>
  <body>
    <div id="someelement"></div>
  </body>
</html>

Upvotes: 1

epascarello
epascarello

Reputation: 207501

Use animation-delay to set a delay before it starts to run. I set it to a big number just so you can see the delay.

document.querySelector('button')
  .addEventListener('click', event => {
    event.preventDefault()
    const classList = event.target.classList
    classList.toggle('spacer')
    classList.toggle('spinner')
  })
.spacer{
    transition: .3s !important;
    padding-right: 3.1rem !important;
}

.spinner{
    border: 5px solid #f3f3f3;
    border-radius: 50%;
    border-top: 5px solid #3498db;
    width: 10px;
    height: 10px;
    animation: spin 2s linear infinite;
    animation-delay: 2s;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
<button></button>

Upvotes: 0

mausinc
mausinc

Reputation: 537

you could add the second class with a short timeout.this gives you also the possibility to add some animations if needed.

window.setTimeout(function() {
  button.addClass("spinner");
},500);

promises will work to

Upvotes: 2

Related Questions