'Modernize Javascript code for a dropdown menu animation
In a post related to another questiona a user suggested me to modernize the js code. Use specifically x.classList.includes()
, x.classList.add()
, and x.classList.remove()
.
So I tried to follow the suggestion and did what you see below. The dropdown menu works well, the only doubt that remains is how to implement x.classList.includes()
? Although everything works as it should I would like to understand if I can improve the code further.
Also I wanted to understand what is the difference between the old and new code? Are there any changes in performance, functionality or anything else? Sorry but I'm new, I'm trying to learn and stack is very useful.
Also I wanted to ask, how can I add an icon to the button that changes when the menu is open or closed ? Here you find the question about the icon, if you can help me I would appreciate it. How to add animate icon menu dropdown open / closed
Apologize for bad English, I'm not doing very well.
Project: https://jsfiddle.net/Snorlax93x/v0c39heo/2/
Old Js code
var menu = document.querySelector(".user_menu_button");
function myFunction() {
var x = document.getElementById("Demo");
if (x.className.indexOf("w3-show") == -1) {
x.className += " w3-show";
} else {
x.className += " w3-hide";
setTimeout(function(){
x.className = x.className.replace(" w3-show", "");
x.className = x.className.replace(" w3-hide", "");
}, 100)
}
}
New Js Code
var menu = document.querySelector(".user_menu_button");
function myFunction() {
var x = document.getElementById("Demo");
if (x.className.indexOf("w3-show") == -1) {
x.classList.add ("w3-show");
} else {
x.classList.add("w3-hide");
setTimeout(function(){
x.classList.remove("w3-show");
x.classList.remove("w3-hide");
},100)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|