3

I'm using JavaScript to style a <span> tag (that is already styled in CSS to be cyan) to turn green when it is clicked, and then right back to cyan. In the CSS, its transition-duration property is set to 100ms. I don't want Javascript to set the color back to cyan before it's finished changing to green, so naturally, I use a setTimeout() to delay it the amount of time that the transition will take (100ms), as you can see in the code below, and I improved it a little after looking at other questions regarding this, but they still didn't seem to be the most efficient.

Code:

// Script is here and not in src in order to make it easier for you to copy and test run.
document.getElementById("text").addEventListener("click", function() {
    document.getElementById("text").style.color = "Green";
    setTimeout(function() {document.getElementById("text").style.color = "Cyan";}, 100); // Timeout time same as transition-duration.
});
#info-display{
    user-select: none;
    text-align: center;
    font: small-caps bold 5vw 'Courier New', Courier, monospace;
}
#text {
    color: Cyan;
    background-color: Black;
    padding: 0.1vw 1vw 0.1vw;
    border-radius: 25% 25% 15% 15%;
    transition-duration: 100ms;
}
<h1 id="info-display"><span id="text">~ Words to Click. ~</span></h1>

I need to know if there is a better way than this; some way that JavaScript can detect when a CSS transition has finished, so that the tedious work of changing the transition time in two places does not have to happen.
If anybody can help me find a way, it would be fantastic! 😃
Thanks!

P.S. Please don't bother asking, "Why an <h1> tag?" or anything like that, it's just what I'm using in the full program that this is for.

1

1 Answer 1

3

Yes, there is. Take a look at the following EventListener:

elem.addEventListener('transitionend', function(){
    //Do something
});
Sign up to request clarification or add additional context in comments.

5 Comments

😂 Thank you, I just found out about this before returning here and seeing this. 👍
I don't understand it actually, what is the (event) => supposed to represent?
@RobertBradley You don't need that there, I edited my answer to make it (hopefully) more simple. You can also take a look at developer.mozilla.org/en-US/docs/Web/API/Element/… for more info.
And elem is just the element upon which you applied the transition
Yeah, okay, I was just testing it because I was unsure if it would work for functions too, since you didn't put that at first. Thank you for all your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.