How to make a website light/dark toggle with CSS & JS

  Рет қаралды 118,125

Kevin Powell

Kevin Powell

4 жыл бұрын

A look at how to create a dark mode toggle switch using JS, which saves the person's preference in localStorage for the next time they visit.
Code from this video: codepen.io/kevinpowell/pen/EM...
///// Change to dark mode using a media query instead! • Dark mode with a media...
---
Come and hangout, ask questions, suggest ideas, and meet some awesome people over in The Community: / discord
I have a newsletter! www.kevinpowell.co/newsletter
I've been working on some courses! Find out more: www.kevinpowell.co/courses
---
My Code Editor: VS Code - code.visualstudio.com/
How my browser refreshes when I save: • How to automatically r...
---
Support me on Patreon: / kevinpowell
I'm on some other places on the internet too!
If you'd like a behind the scenes and previews of what's coming up on my KZbin channel, make sure to follow me on Instagram and Twitter.
Instagram: / kevinpowell.co
Twitter: / kevinjpowell
Codepen: codepen.io/kevinpowell/
Github: github.com/kevin-powell

Пікірлер: 147
@deathtoby
@deathtoby 2 жыл бұрын
Hi Kevin. I think you may have made a mistake here. localStorage will always convert your value to string. So when you set it as null, it will convert it to "null" instead and that will always return true. Although you did not check on it but it may not be the best practice here. You would need to use .removeItem instead if you want it to be null or undefined
@ConorBailey
@ConorBailey 4 жыл бұрын
Awesome. I love how you explain clearly what the code is doing. Thanks Kevin!
@chrisicotec7652
@chrisicotec7652 2 жыл бұрын
this channel has made me fall in love with CSS again... not so much the projects on the channel but for the use of vs code, i shunned it for years heavily favouring notepad++ s my tool of choice , now vs code is my first choice
@schism1986
@schism1986 2 жыл бұрын
I've been a professional frontend developer for years and I still learn new tricks from you in every single one of your videos! Thank you for your work!
@mirjalol49
@mirjalol49 7 ай бұрын
u are not pro then
@schism1986
@schism1986 7 ай бұрын
@@mirjalol49 lol ok
@JohnWick-id6pk
@JohnWick-id6pk 3 жыл бұрын
Thank you for the tutorial! I have used the code to do dark mode and modified it to make a switch which does visual JS functions
@pankam7800
@pankam7800 4 жыл бұрын
@Kevin Powell is the KING explainer for CSS in KZbin..!!!
@busyrand
@busyrand 4 жыл бұрын
I need this. Thanks a million times! The local storage part is great.
@aaranragu
@aaranragu 4 жыл бұрын
Thank you sooo sooo much for this tutorial. I had a school project on making a website and I'm so grateful I'm able to implement this feature with the help of amazing such as this one
@Shizuko-Zen
@Shizuko-Zen 3 жыл бұрын
Thank you so much! Subscribed! This is one of the clearest videos I've ever seen! I'll have to check out more of your videos!
@siriusgd4753
@siriusgd4753 4 жыл бұрын
That is wonderful Kevin. I've been meaning to create a process for selecting different themes for my website and I think this will help immensely with the coding.
@ourcore
@ourcore 4 жыл бұрын
This was incredibly helpful and informative. Thanks, Kevin!
@jlogo80
@jlogo80 4 жыл бұрын
Awesome, clear and useful like always Kevin. Many thanks
@Nikhil-kr8rx
@Nikhil-kr8rx 3 жыл бұрын
you're legend...... YOU ARE LEGEND sir i was struggling with this for a week now. But thanks to you, now i can continue my project further. THANK YOU!
@rogerluiz3450
@rogerluiz3450 3 жыл бұрын
Amazing video! I'm from Brazil and i watch your videos to learning programming!
@sskdev5116
@sskdev5116 4 жыл бұрын
Wow you simplified it sooo much. Thank you!!!
@moekaba
@moekaba 2 жыл бұрын
Thank you so much Kevin! This video was very helpful.
@sougataghar1179
@sougataghar1179 4 жыл бұрын
you gave me a new idea for writting functions , thanks
@njourawebdev
@njourawebdev 2 жыл бұрын
thank you for your amazing content!!!! straight to the point plus a great way to explain
@anastasiyaboiko8862
@anastasiyaboiko8862 3 жыл бұрын
Thank you, I finally figured out how to do my homework
@ForeverNoTube
@ForeverNoTube 2 жыл бұрын
Your videos are so great! Thank you-- this helped a lot!
@rosaclovis
@rosaclovis 4 жыл бұрын
Great video Kevin! Thank you for sharing!
@MARIUTSKI13897
@MARIUTSKI13897 4 жыл бұрын
Didn't know that simple thing about css variables: you can change their values :'v. As always, you opened my eyes, Kevin, thanks a lot!
@bibakomk
@bibakomk 6 ай бұрын
Amazing I learned so much from this video thanks for sharing!
@emiklad2594
@emiklad2594 4 жыл бұрын
thank You Kevin, You make the world a better place...
@JFishh_
@JFishh_ 2 жыл бұрын
Hi, not sure if you'll see this but regardless, I wanted to drop a comment to say thanks for this video. I'm currently at the end stage of a university project in which I'm building a web-app and I really wanted to include dark mode as a feature to put my own spin on things. I couldn't figure out how to do it and then I found this video of yours which has been an awesome help, so I really appreciate it. Very happy to be able to have a working dark mode now that stays consistent across pages.
@sonsofdarmy4325
@sonsofdarmy4325 2 жыл бұрын
Thank you so much this was helpful you got a new subscriber
@gabeadams2926
@gabeadams2926 4 жыл бұрын
Awesome tutorial man! Appreciate it
@darcvm7716
@darcvm7716 3 жыл бұрын
Thank you Sir!! You don't know how this came handy.
@eplusplus
@eplusplus 2 жыл бұрын
Thanks! Exactly what I needed.
@juliagowacka8099
@juliagowacka8099 3 ай бұрын
omg thank you for this video 🥰so helpful
@KyleMerl
@KyleMerl 4 жыл бұрын
good tutorial! Local storage is pretty cool. I used it for an "under construction" modal for my website, so visitors would only see the modal the first time they came to my site. You can do a lot of things with it.
@rocioalonso7490
@rocioalonso7490 2 жыл бұрын
amazing! this was really helpful! thank you
@muhammadfaiz9409
@muhammadfaiz9409 3 жыл бұрын
Your teaching technique is awesome sir 👌
@KevinPowell
@KevinPowell 3 жыл бұрын
Thanks a lot 😊
@hectorserrano9314
@hectorserrano9314 4 жыл бұрын
Great Video, as always. You should consider posting the CSS code as well, I wanted to take a look to see where the classes where getting added and removed when the JS fired. Love your content Kevin!
@KevinPowell
@KevinPowell 4 жыл бұрын
I forgot the link to my CodePen! codepen.io/kevinpowell/pen/EMdjOV
@MariuszZakrzewski
@MariuszZakrzewski 4 жыл бұрын
Great! Thank you! It's a best solution for my problem.
@SamuelHauptmannvanDam
@SamuelHauptmannvanDam 2 жыл бұрын
Just what I needed.
@mukhammadsyukronazim7248
@mukhammadsyukronazim7248 2 жыл бұрын
really helpful, big thanks for you! cheers!🍹
@xircle
@xircle 2 жыл бұрын
Great tutorial!
@habibthekhan
@habibthekhan 2 жыл бұрын
this is the best video this helped me a lot thanks and plz try to make more js videos you are a good js teacher. THANKS, A LOT
@saschab.5154
@saschab.5154 Жыл бұрын
Thank you so much! Maybe you can make a playlist one day: "Useful scripts to avoid extra WordPress plugins." Thanks for saving me from yet another plugin...
@chintansawla
@chintansawla 3 жыл бұрын
Thank you for the video!! 🙌
@attractiveguy6495
@attractiveguy6495 4 жыл бұрын
he explains it sooo good those
@farhan-app
@farhan-app 2 жыл бұрын
Please do more videos like this!
@chriscrowd4946
@chriscrowd4946 4 жыл бұрын
Excellent video!
@daviluiz5849
@daviluiz5849 2 жыл бұрын
Awesome video.
@oussamaKHB
@oussamaKHB 3 жыл бұрын
Thanks dude, just in the point
@TheGorillafoot
@TheGorillafoot 4 жыл бұрын
This is sweet. Thanks!
@AlefyPimentel
@AlefyPimentel 3 жыл бұрын
Great video, thank you.
@SuperMegaEgg
@SuperMegaEgg 2 жыл бұрын
Great video, thank-you.
@indietuts
@indietuts 2 жыл бұрын
This is what, I'm looking for.
@nipunlakshank
@nipunlakshank Жыл бұрын
KZbin algorithm now scans my brain to see what's I'm thinking. I just had a thought of implementing a dark mode toggle and before even I search any kind of thing about that this came in the feed. Bruh this is too scary now!
@handrihmw
@handrihmw 4 жыл бұрын
Thanks Kevin!
@basutheartist
@basutheartist 4 жыл бұрын
Wow ! Kevin really cool and powerfulll
@DanielCruz-se3bf
@DanielCruz-se3bf 2 жыл бұрын
You are the Goat 🐐
@sonnyl2915
@sonnyl2915 Жыл бұрын
Thank you!
@LanFeusT23
@LanFeusT23 4 жыл бұрын
Great video! It would be awesome if some of those examples you made were on codepen or alike and linked in the description! :D
@KevinPowell
@KevinPowell 4 жыл бұрын
I forgot to add it! codepen.io/kevinpowell/pen/EMdjOV
@shekhsaifuddin1353
@shekhsaifuddin1353 4 жыл бұрын
Wow, it's awesome....💙💙💙
@mrMinstrel
@mrMinstrel 4 жыл бұрын
Super! Thanks
@WePiphany
@WePiphany 10 ай бұрын
I was having trouble getting this to work on a WordPress + Divi site. I had to wrap the script in an event listener that listens for the DOMContentLoaded event. This let me put the script in the head.
@toano8855
@toano8855 3 жыл бұрын
thanks for your video
@LadyLexyStarwatcher
@LadyLexyStarwatcher 2 жыл бұрын
Love this and going to use it. I only have one complaint, every time a page loads I get blinded by a flash of light before it applies the dark theme
@spicybaguette7706
@spicybaguette7706 4 ай бұрын
I may be a little late, but this is because your script is not executed immediately. The browser starts rendering before it runs your script, and so your script doesn't have the time to set dark mode. The way you can fix this is by writing an inline script that just reads the value from localstorage and sets the theme on your website to prevent the flashbang It's usually a good thing that scripts don't block the browser rendering as it can be very bad for UX, but in this case you actually need it. But just a tiny inline script should be enough This one-liner should do the trick: document.documentElement.classList.toggle("dark", localStorage.theme==="dark") If you want to take into account the system preference as a fallback: document.documentElement.classList.toggle("dark", localStorage.theme ? localStorage.theme==="dark" : matchMedia("(prefers-color-scheme: dark)").matches)
@Jarrod0067
@Jarrod0067 7 ай бұрын
Using :root custom properties with the new prefers-color-scheme media query overrides makes it a cakewalk to implement robust CSS without any JS, which is absolutely crazy
@santiagopabloortiz6322
@santiagopabloortiz6322 2 жыл бұрын
Nice!
@LeoStephanou
@LeoStephanou 7 ай бұрын
I've been trying to get this working across other pages, and finally realised I just needed to put the script before the closing body tag....which is clear in this video :/ I did have it at the bottom for the first page, but didn't realise I have my script in the head section for the other pages...just fyi :D
@iamaakashbasnet
@iamaakashbasnet 4 жыл бұрын
Thanks!
@alexandralml9554
@alexandralml9554 Жыл бұрын
i love you!!
@SomeOne-lj7fl
@SomeOne-lj7fl 3 жыл бұрын
The code in this video has a flashing problem on page load where it quickly flashes original page colors then dark mode colors when in dark mode. Here is what I did to prevent flashing. Put some code in the head tag and some in the body tag. Make sure the class darkMode is applied to the main tag. if (localStorage.getItem('darkMode') === null){ document.documentElement.classList.remove('darkmode'); } if (localStorage.getItem('darkMode') === '1') { document.documentElement.classList.add('darkmode'); } if (localStorage.getItem('darkMode') === '0') { document.documentElement.classList.remove('darkmode'); } document.querySelector('#dark-mode-toggle').addEventListener('click', function() { var darkMode = localStorage.getItem('darkMode'); if (darkMode === null){ localStorage.setItem('darkMode', '1'); document.documentElement.classList.add('darkmode'); } if (darkMode === '1'){ localStorage.setItem('darkMode', '0'); document.documentElement.classList.remove('darkmode'); } if (darkMode === '0'){ localStorage.setItem('darkMode', '1'); document.documentElement.classList.add('darkmode'); } });
@georgegudgeon5695
@georgegudgeon5695 2 жыл бұрын
Hi, I noticed the problem you said, but when I use the code you've put it just keeps the pages permanently in dark mode, are there any other differences from what you added and the original? Thanks
@Eslwitch
@Eslwitch 2 жыл бұрын
God bless you kind man
@ImTheDot
@ImTheDot Жыл бұрын
Awesome
@PainMajesty
@PainMajesty 3 жыл бұрын
Thanks, this works perfectly but anytime I reload my page with darkMode enabled the page will first appear in light mode and automatically do the transition to darkMode so the user can see the light mode for a split second before it changes. anyone knows how I can fix that?
@gwenaeloppitz3972
@gwenaeloppitz3972 4 жыл бұрын
hey thanks for your video! I did something similar and works fine but I would like to leave my html file as empty as possible? Could you tell us how to transfer this in a typescript or javascript file? thanks
@aaranragu
@aaranragu 4 жыл бұрын
Is it possible to change the source of an image when I turn on darkmode?
@DerMBen
@DerMBen 2 жыл бұрын
Is there a way to use this in combination with the media query? Would be interesting to see a way to stop the two from conflicting (or maybe they won't - I'm fairly new to this) I just noticed your codepen of this example doesn't seem to react to the device theme.
@JaeTLDR1
@JaeTLDR1 2 жыл бұрын
I would simply do the media query by default and if the localstorage item exists then use its value as the theme (‘dark’/‘light’) or true/false
@cogaming6131
@cogaming6131 2 жыл бұрын
thanks you very much ♥♥♥ cảm ơn bạn nhiều ♥♥
@Semilore317
@Semilore317 Жыл бұрын
Hi, I really love your html and css videos, but I was hoping you could do a JavaScript series. I'm struggling with it a little and I need your help.
@codingchewie
@codingchewie 3 жыл бұрын
Interesting video but instead of a disable and enable function couldn't the not operator be used so you would only need a single function?
@bubye6859
@bubye6859 Жыл бұрын
I basically written all of the code as you did and added it to my website and while i click the button colors are changing, but after i click another time they just stay in darkmode and after refreshing they get back to default light mode web page colors. Any ideas why could this be happening?
@hanzcorpuz2358
@hanzcorpuz2358 3 жыл бұрын
Thanks! This was really helpful. How would we make this so that this can work for multiple buttons? I'd like a separate button to do the same. But only the first button works.
@KevinPowell
@KevinPowell 3 жыл бұрын
You'd have to use a `querySelectorAll` instead of a querySelector, but that gives you back a node list, so you'd have to loop through that to set the event listener for each one
@elmomahupil
@elmomahupil 3 жыл бұрын
THANKYOUUUUUUUUUUUUU
@hamzaal-najdawi4382
@hamzaal-najdawi4382 3 жыл бұрын
Can you make a video to make the dark mode to all pages Like the button is in the home page when you click it the dark mode well be on all pages
@aaranragu
@aaranragu 4 жыл бұрын
Can I pass the darkmode setting through the next pages for my website?
@kawcco
@kawcco 4 жыл бұрын
Is it possible to have the media query and JS to coexist, so if a user has dark mode enabled on their OS, but prefers the color scheme of light mode, they can switch it and have it stay that way?
@KevinPowell
@KevinPowell 4 жыл бұрын
Well, if they had prefers dark, but used this switch, wouldn't it work? You could use prefers-color-scheme to set the default maybe?
@SpaceDoodle2008
@SpaceDoodle2008 Жыл бұрын
I think that new :has() pseudo-class will make it much easier by throwing a body:has(#design-select-dark:checked) { --background: var(--darkmode-background-color); } and so on.
@vigramvasi442
@vigramvasi442 2 жыл бұрын
How do I change the image src and onerror src when dark mode is enabled, please help me with this.
@kunaltanwar2885
@kunaltanwar2885 3 жыл бұрын
Hey Man first of all Great Video. And secondly is when I'm running this code using live server the code is not working! What i mean is after switching it in dark mode i closed the browser and when i start it again it was still in light mode! Please Help me out ASAP!
@buivano3895
@buivano3895 3 жыл бұрын
good
@ramanasketches54
@ramanasketches54 2 ай бұрын
why does page flickering happens when we try localstorage and how to stop it. it happens when I try dark mode using the above code
@aqua-bery
@aqua-bery 27 күн бұрын
Why did you declare the enableDarkMode and disableDarkMode with the const enableDarkMode = () => { }, instead of just saying "function enableDarkMode(){}"? Im new to javascript and this is kinda confusing
@DominicRossYD33
@DominicRossYD33 2 жыл бұрын
Really well explained video, thank you! Out of interest, does that local storage only apply to your website (ie: the one you're setting the dark mode for) or could any website use it (assuming they used the same variable name)?
@etekweb
@etekweb 2 жыл бұрын
Local storage only applies to the current domain, so only your website.
@Diablerick
@Diablerick 2 жыл бұрын
I get a flash when I change pages on my site. Does anyone have solve this yet?
@manuelkoch5359
@manuelkoch5359 2 жыл бұрын
Hello Kevin, great content❤ It is worth mentioning that localStorage and also sessionStorage access should always be wrapped in try/catch blocks because sometimes it will throw an error. For example in Safaris inkognito tabs there is no storage which would crash the code
@DoctorMeatDoesHousecalls
@DoctorMeatDoesHousecalls 4 ай бұрын
Local storage still gives me a flash bang every time I reload the page. Dropping a bit of code in the head to delay page load doesn’t work for me either.
@bintangnaufal
@bintangnaufal Жыл бұрын
does anyone knows how to combine the media query method and this method because i thought this video was a continuation but instead just shows another method
@bintangnaufal
@bintangnaufal Жыл бұрын
because i've spent time reconstructing my navbar in every pages to add that one button as a toggle i dont want to regret that :)))))
@MatthewKennedyUK
@MatthewKennedyUK 3 жыл бұрын
Is there any way around the flash of light mode as the javascript executes on a page refresh?
@KevinPowell
@KevinPowell 3 жыл бұрын
If there is, I don't know about it. Even YT which uses a media query (I think?) has a flash every time I visit it before it goes to dark mode.
@MatthewKennedyUK
@MatthewKennedyUK 3 жыл бұрын
@@KevinPowell I’m working on an admin UI and the user has to be logged in to access it, so I’ve decided to go directly into the code the generates html. The user can select and save their UI preference and the appropriate class is rendered straight in the html on load.
@MatthewKennedyUK
@MatthewKennedyUK 3 жыл бұрын
@@KevinPowell I remember from looking at mmenu.js there was some css to stop the flash of unstyled menu as the JS loads, but it will be bad practice to use display none on the body. So basically unless the JavaScript has added a mode-loaded class the body would be hidden body:not( .mode-loaded) { display: none; } Probably a bad idea, but would work in theory.
@nimrodnorway3023
@nimrodnorway3023 2 жыл бұрын
One more question, on pages with a heavy page load - will there be a flickering? Because it can take some time before everything is rendered and the JavaScript gets executed.
@KevinPowell
@KevinPowell 2 жыл бұрын
It's very possible, yes. You could use the color-scheme meta, and assuming they use the toggle to match their system preferences (which I'm guessing is most people), it should help prevent the flash. Or at least as drastic of a flash, depending on the color scheme being used).
@bytecodeman1
@bytecodeman1 4 жыл бұрын
Not too familiar with SVG. How do you generate that SVG code?
@pawpaaj
@pawpaaj 4 жыл бұрын
For example you can export it from such programs as Adobe Illustrator.
@neekowo
@neekowo 2 жыл бұрын
6:05 when i test the button, the console gave me an error "Uncaught TypeError: darkModeToggle is null" can anyone help please
@sjspstudio9524
@sjspstudio9524 3 жыл бұрын
How to get localstorage value in asp.net code behind
@nimrodnorway3023
@nimrodnorway3023 2 жыл бұрын
I'd just like to add that both SVGs (click here and the icon) should have aria-hidden set to true so screen readers don't get confused by it.
@KevinPowell
@KevinPowell 2 жыл бұрын
That's true. I should have also used an aria-label on the button as well.
@YPremSingha
@YPremSingha 4 жыл бұрын
Awesome work, But why it's not working on my Safari ... 'QuotaExceededError'
Introduction to the Intersection Observer JavaScript API
22:11
Kevin Powell
Рет қаралды 174 М.
How to create a theme switcher with HTML & CSS
28:21
Kevin Powell
Рет қаралды 108 М.
Increíble final 😱
00:37
Juan De Dios Pantoja 2
Рет қаралды 14 МЛН
Miracle Doctor Saves Blind Girl ❤️
00:59
Alan Chikin Chow
Рет қаралды 69 МЛН
Be kind🤝
00:22
ISSEI / いっせい
Рет қаралды 23 МЛН
You’re doing dark mode wrong!
7:54
Coding in Public
Рет қаралды 43 М.
Toggle Button Without HTML, CSS Or Javascript (Full Tutorial in Description)
0:11
NewForm with Brandon Groce
Рет қаралды 339 М.
How To Build An Advanced Light/Dark Theme Toggle
25:46
Web Dev Simplified
Рет қаралды 87 М.
Top 10 CSS One Liners That Will Blow Your Mind
13:34
developedbyed
Рет қаралды 900 М.
Avoid these 5 beginner CSS mistakes
21:38
Kevin Powell
Рет қаралды 61 М.
Give your site a fantastic color scheme fast
25:55
Kevin Powell
Рет қаралды 322 М.
Using CSS custom properties like this is a waste
16:12
Kevin Powell
Рет қаралды 158 М.
Subtle, yet Beautiful Scroll Animations
5:04
Beyond Fireship
Рет қаралды 1,6 МЛН
The Story of Next.js
12:13
uidotdev
Рет қаралды 535 М.
How to take control of Flexbox
16:01
Kevin Powell
Рет қаралды 104 М.
Increíble final 😱
00:37
Juan De Dios Pantoja 2
Рет қаралды 14 МЛН