+ 1

Toggle Javascript

Greetings, everyone! It's been years since I've written a piece of code, so I thought I'd give it a try. I'm pretty sure I know how to write a toggle function, so I'm curious as to why these two examples don't work. https://sololearn.com/compiler-playground/W639upiF8RJ5/?ref=app

9th Mar 2024, 7:17 PM
Vasilis Karapas
Vasilis Karapas - avatar
4 Réponses
+ 3
The screenC variable is not an html div element, as you might think, it's just a regular string variable that stores the name of the color. So you need to assign it to the html element at the end of the condition: screen.style.backgroundColor = screenC; An example of how the .toggle() method works: https://sololearn.com/compiler-playground/WcpqWngj9h4u/?ref=app
9th Mar 2024, 10:02 PM
Solo
Solo - avatar
+ 3
Yeah, I'm definitely rusty. Especially now, when there are a lot of easier ways to do this. Thank you so much for your help!
9th Mar 2024, 10:31 PM
Vasilis Karapas
Vasilis Karapas - avatar
+ 2
<!DOCTYPE html> <html> <head> <title>Screen Toggle</title> <style> div{ width: 100px; height: 100px; } </style> </head> <body> <div></div> <script> const screen = document.querySelector("div"); let screenC = screen.style.backgroundColor = "purple"; let tgl = true; /* screen.addEventListener("click", tap); function tap(){ if(tgl){ tgl = false; screenC = "black"; } else{ tgl = true; screenC = "purple"; } } */ screen.onclick =()=>{ if(tgl){ tgl = false; screenC = "black"; } else{ tgl = true; screenC = "purple"; } }; </script> </body> </html>
9th Mar 2024, 9:39 PM
Vasilis Karapas
Vasilis Karapas - avatar
+ 2
Function toggle(el) { // Disactive el.style.display = "none"; // Active el.style.display = "block"; //flex, inline, inline-block }
10th Mar 2024, 7:17 PM
Kamomiruku
Kamomiruku - avatar