Home > Back-end >  How to add animation to the display none -> block in javascript
How to add animation to the display none -> block in javascript

Time:12-27

I have a code which is exposing and hiding the button

HTML

<div id="butStyle">
     <button id="langBut">Язык</button>
     <button id="en"><img src="image/en.png" alt="en" height="20px" width="30px"></button>
</div>

JS

document.getElementById('en').style.display = 'none';

function displayONLang(){
    document.getElementById('en').style.display = 'block';
}
function displayOFFLang(){
    document.getElementById('en').style.display = 'none';
}
document.getElementById("butStyle").addEventListener("mouseover",displayONLang); 
document.getElementById("butStyle").addEventListener("mouseout",displayOFFLang); 

So i need to add the smooth animation to this process with javascript, but idk how Any suggestions?

CodePudding user response:

The easiest approach would be to fade in/out so instead of using display as it can't be animated, you could animate either width/height or opacity.

Here's code with solution by animating opacity:

document.getElementById('en').style.opacity = '0';
document.getElementById('en').style.transition = '250ms opacity ease';

function displayONLang(){
    document.getElementById('en').style.opacity = '1';
}
function displayOFFLang(){
    document.getElementById('en').style.opacity = '0';
}
document.getElementById("butStyle").addEventListener("mouseover",displayONLang); 
document.getElementById("butStyle").addEventListener("mouseout",displayOFFLang);

In this code in the second line I also added transition mode which you can customize to your liking:

document.getElementById('en').style.transition = '250ms opacity ease';

This is a CSS attribute that allows for smooth transitions between states, you can read more about it here.

  • Related