I've never used nested functions before, and this seemingly simple task is giving me trouble. When I run this code, only the first function works, and the second is completely unresponsive (but doesn't give me an error message). What am I doing wrong?
function toggleMobileMenu() {
setTimeout(function showMobileMenu() {
var x = document.getElementById("content");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}, 1000);
function toggleClasses() {
var element = document.getElementById("myNav");
element.classList.toggle("fixed");
var element = document.getElementById("overlay");
element.classList.toggle("fixed");
var element = document.getElementById("site-header");
element.classList.toggle("fixed");
}
}
As @rayhatfield mentions in the comments you need to invoke the function so that it executes.
If the function is defined inside another function (nested) like it is in this case, but it is not invoked or called, then it wont execute.
function toggleMobileMenu() {
setTimeout(function showMobileMenu() {
var x = document.getElementById("content")
if (x.style.display === "none") {
x.style.display = "block"
} else {
x.style.display = "none"
}
}, 1000)
function toggleClasses() {
var element = document.getElementById("myNav")
element.classList.toggle("fixed")
var element = document.getElementById("overlay")
element.classList.toggle("fixed")
var element = document.getElementById("site-header")
element.classList.toggle("fixed")
}
toggleClasses() // <--- invoke the function
}
The first part works properly because setTimeout() makes a callback to the function passed to the parameters after a certain amount of milliseconds. And then nothing happens because you are just defining a function inside another function.