Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
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)
  }
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!