I have been trying to toggle the background colour of the button as like changing the margin, for some reason margin works and btn
colour doesn't.
<script>
let myBtn = document.querySelector("#menuBtn");
function myFunction1() {
var Menubase = document.getElementById("list-menu-base");
if (Menubase.style.marginTop==="0px") {
Menubase.style.marginTop="-250px";
} else {
Menubase.style.marginTop="0px";
}
}
myBtn.onclick = myFunction1;
// The above function works bu not the one follows//
function myFunction3() {
var Menubase = document.getElementById("menuBtn");
if (Menubase.style.backgroundColor==="red") {
Menubase.style.backgroundColor="#FF7E00";
} else {
Menubase.style.backgroundColor="#FF7E00";
}
}
myBtn.onclick = myFunction3;
</script>
Regardless of your code inside each function.
You can't have two onClick
Events for the same element.
Wrap your two functions with one container function like:
function fullFunction() {
myFunction1();
myFunction3();
}
myBtn.onclick = fullFunction;
Second: You should add the color in rgb
on your javascript code instead of hex
.
Demo:
let myBtn = document.querySelector("#menuBtn"); function myFunction1() { var Menubase = document.getElementById("list-menu-base"); if (Menubase.style.marginTop === "0px") { Menubase.style.marginTop = "25px"; } else { Menubase.style.marginTop = "0px"; } } function myFunction3() { var myBtn = document.getElementById("menuBtn"); if (myBtn.style.backgroundColor === "rgb(142, 253, 27)") { myBtn.style.backgroundColor = "rgb(255, 103, 0)"; } else { myBtn.style.backgroundColor = "rgb(142, 253, 27)"; } } function fullFunction() { myFunction1(); myFunction3(); } myBtn.onclick = fullFunction;
#menuBtn { background-color: rgb(255, 103, 0); padding: 10px 15px; text-decoration: none; color: white; margin-top: 100px; } #list-menu-base { background-color: antiquewhite; width: 100%; height: 50px; }
<div id="list-menu-base"></div> <a id="menuBtn" href="#">MENU BUTTON</a>
You need fix your js
function myFunction3() {
var Menubase = document.getElementById("menuBtn");
// Don't exists red color, so u can try use the rgb
if (Menubase.css('color') == 'rgb(255, 0, 0)') {
Menubase.style.backgroundColor = "rgb(255,126,0)";
} else {
Menubase.style.backgroundColor = "rgb(255,126,100)";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.