How to animate toggle between menu and close Material Icons using CSS and JavaScript? [duplicate]

2 days ago 1
ARTICLE AD BOX

I am creating a navigation toggle button for my website. I want to switch between the menu and close Material Icons when the button is clicked. The icon changes correctly using JavaScript, but the transition happens instantly without animation. How can I add a smooth animation effect when switching between the icons?

<!DOCTYPE html> <html> <head> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <style> #menuIcon{ font-size:40px; cursor:pointer; transition: transform 0.3s ease; } .rotate{ transform: rotate(180deg); } </style> </head> <body> <span id="menuIcon" class="material-icons">menu</span> <script> const icon = document.getElementById("menuIcon"); icon.addEventListener("click", function() { if (this.textContent === "menu") { this.textContent = "close"; } else { this.textContent = "menu"; } this.classList.toggle("rotate"); }); </script> </body> </html>

VIVEK TAWARE's user avatar

New contributor

VIVEK TAWARE is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

3

Read Entire Article