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

Sdílet
Vložit
  • čas přidán 22. 10. 2019
  • 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 CZcams channel, make sure to follow me on Instagram and Twitter.
    Instagram: / kevinpowell.co
    Twitter: / kevinjpowell
    Codepen: codepen.io/kevinpowell/
    Github: github.com/kevin-powell

Komentáře • 147

  • @ConorBailey
    @ConorBailey Před 4 lety +4

    Awesome. I love how you explain clearly what the code is doing. Thanks Kevin!

  • @deathtoby
    @deathtoby Před 3 lety +42

    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

  • @chrisicotec7652
    @chrisicotec7652 Před 2 lety +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

  • @busyrand
    @busyrand Před 4 lety +2

    I need this. Thanks a million times! The local storage part is great.

  • @JohnWick-id6pk
    @JohnWick-id6pk Před 3 lety +1

    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

  • @JFishh_
    @JFishh_ Před 2 lety

    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.

  • @MARIUTSKI13897
    @MARIUTSKI13897 Před 4 lety +2

    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!

  • @aaranragu
    @aaranragu Před 4 lety

    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 Před 3 lety

    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!

  • @ourcore
    @ourcore Před 4 lety

    This was incredibly helpful and informative. Thanks, Kevin!

  • @siriusgd4753
    @siriusgd4753 Před 4 lety +3

    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.

  • @pankam7800
    @pankam7800 Před 4 lety

    @Kevin Powell is the KING explainer for CSS in CZcams..!!!

  • @jlogo80
    @jlogo80 Před 4 lety +1

    Awesome, clear and useful like always Kevin. Many thanks

  • @Nikhil-kr8rx
    @Nikhil-kr8rx Před 3 lety

    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!

  • @KyleMerl
    @KyleMerl Před 4 lety

    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.

  • @rogerluiz3450
    @rogerluiz3450 Před 3 lety

    Amazing video! I'm from Brazil and i watch your videos to learning programming!

  • @schism1986
    @schism1986 Před 2 lety +6

    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!

  • @njourawebdev
    @njourawebdev Před 2 lety

    thank you for your amazing content!!!!
    straight to the point plus a great way to explain

  • @hectorserrano9314
    @hectorserrano9314 Před 4 lety +1

    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  Před 4 lety

      I forgot the link to my CodePen! codepen.io/kevinpowell/pen/EMdjOV

  • @sougataghar1179
    @sougataghar1179 Před 4 lety +1

    you gave me a new idea for writting functions , thanks

  • @anastasiyaboiko8862
    @anastasiyaboiko8862 Před 3 lety +6

    Thank you, I finally figured out how to do my homework

  • @moekaba
    @moekaba Před 3 lety

    Thank you so much Kevin! This video was very helpful.

  • @sskdev5116
    @sskdev5116 Před 4 lety

    Wow you simplified it sooo much. Thank you!!!

  • @ForeverNoTube
    @ForeverNoTube Před 2 lety

    Your videos are so great! Thank you-- this helped a lot!

  • @rosaclovis
    @rosaclovis Před 4 lety

    Great video Kevin! Thank you for sharing!

  • @darcvm7716
    @darcvm7716 Před 3 lety

    Thank you Sir!! You don't know how this came handy.

  • @emiklad2594
    @emiklad2594 Před 4 lety

    thank You Kevin, You make the world a better place...

  • @gabeadams2926
    @gabeadams2926 Před 4 lety

    Awesome tutorial man! Appreciate it

  • @sonsofdarmy4325
    @sonsofdarmy4325 Před 3 lety +1

    Thank you so much this was helpful
    you got a new subscriber

  • @habibthekhan
    @habibthekhan Před 2 lety

    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

  • @bibakomk
    @bibakomk Před 8 měsíci

    Amazing I learned so much from this video thanks for sharing!

  • @MariuszZakrzewski
    @MariuszZakrzewski Před 4 lety

    Great! Thank you! It's a best solution for my problem.

  • @eplusplus
    @eplusplus Před 2 lety +1

    Thanks! Exactly what I needed.

  • @rocioalonso7490
    @rocioalonso7490 Před 2 lety

    amazing! this was really helpful! thank you

  • @muhammadfaiz9409
    @muhammadfaiz9409 Před 4 lety +1

    Your teaching technique is awesome sir 👌

  • @juliagowacka8099
    @juliagowacka8099 Před 5 měsíci

    omg thank you for this video 🥰so helpful

  • @SamuelHauptmannvanDam
    @SamuelHauptmannvanDam Před 2 lety

    Just what I needed.

  • @LanFeusT23
    @LanFeusT23 Před 4 lety +1

    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  Před 4 lety

      I forgot to add it! codepen.io/kevinpowell/pen/EMdjOV

  • @chintansawla
    @chintansawla Před 3 lety

    Thank you for the video!! 🙌

  • @mukhammadsyukronazim7248

    really helpful, big thanks for you! cheers!🍹

  • @TheGorillafoot
    @TheGorillafoot Před 4 lety

    This is sweet. Thanks!

  • @xircle
    @xircle Před 2 lety

    Great tutorial!

  • @attractiveguy6495
    @attractiveguy6495 Před 4 lety

    he explains it sooo good those

  • @chriscrowd4946
    @chriscrowd4946 Před 4 lety

    Excellent video!

  • @handrihmw
    @handrihmw Před 4 lety

    Thanks Kevin!

  • @oussamaKHB
    @oussamaKHB Před 3 lety

    Thanks dude, just in the point

  • @AlefyPimentel
    @AlefyPimentel Před 4 lety

    Great video, thank you.

  • @farhan-app
    @farhan-app Před 2 lety

    Please do more videos like this!

  • @SuperMegaEgg
    @SuperMegaEgg Před 2 lety

    Great video, thank-you.

  • @daviluiz5849
    @daviluiz5849 Před 2 lety

    Awesome video.

  • @shekhsaifuddin1353
    @shekhsaifuddin1353 Před 4 lety

    Wow, it's awesome....💙💙💙

  • @basutheartist
    @basutheartist Před 4 lety

    Wow ! Kevin really cool and powerfulll

  • @saschab.5154
    @saschab.5154 Před rokem

    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...

  • @indietuts
    @indietuts Před 2 lety

    This is what, I'm looking for.

  • @LadyLexyStarwatcher
    @LadyLexyStarwatcher Před 2 lety +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 Před 6 měsíci +1

      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)

  • @sonnyl2915
    @sonnyl2915 Před rokem

    Thank you!

  • @nipunlakshank
    @nipunlakshank Před rokem

    CZcams 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!

  • @mrMinstrel
    @mrMinstrel Před 4 lety

    Super! Thanks

  • @DanielCruz-se3bf
    @DanielCruz-se3bf Před 2 lety

    You are the Goat 🐐

  • @WePiphany
    @WePiphany Před rokem

    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.

  • @juliusmsapija502
    @juliusmsapija502 Před 16 dny

    thx bro, u solve my problem

  • @LeoStephanou
    @LeoStephanou Před 9 měsíci

    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

  • @toano8855
    @toano8855 Před 3 lety

    thanks for your video

  • @Semilore317
    @Semilore317 Před rokem +1

    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.

  • @santiagopabloortiz6322

    Nice!

  • @alexandralml9554
    @alexandralml9554 Před rokem

    i love you!!

  • @SomeOne-lj7fl
    @SomeOne-lj7fl Před 3 lety +10

    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 Před 2 lety

      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

  • @iamaakashbasnet
    @iamaakashbasnet Před 4 lety

    Thanks!

  • @Jarrod0067
    @Jarrod0067 Před 9 měsíci

    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

  • @gwenaeloppitz3972
    @gwenaeloppitz3972 Před 4 lety

    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

  • @PainMajesty
    @PainMajesty Před 3 lety +1

    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?

  • @aaranragu
    @aaranragu Před 4 lety +1

    Is it possible to change the source of an image when I turn on darkmode?

  • @codingchewie
    @codingchewie Před 3 lety

    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?

  • @ImTheDot
    @ImTheDot Před rokem

    Awesome

  • @DerMBen
    @DerMBen Před 2 lety +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 Před 2 lety

      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

  • @hanzcorpuz2358
    @hanzcorpuz2358 Před 3 lety

    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  Před 3 lety

      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 Před 4 lety

    THANKYOUUUUUUUUUUUUU

  • @hamzaal-najdawi4382
    @hamzaal-najdawi4382 Před 3 lety +1

    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

  • @cogaming6131
    @cogaming6131 Před 2 lety

    thanks you very much ♥♥♥ cảm ơn bạn nhiều ♥♥

  • @kunaltanwar2885
    @kunaltanwar2885 Před 4 lety

    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!

  • @manuelkoch5359
    @manuelkoch5359 Před 2 lety

    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

  • @Eslwitch
    @Eslwitch Před 3 lety

    God bless you kind man

  • @bubye6859
    @bubye6859 Před rokem

    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?

  • @aaranragu
    @aaranragu Před 4 lety

    Can I pass the darkmode setting through the next pages for my website?

  • @DominicRossYD33
    @DominicRossYD33 Před 2 lety

    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 Před 2 lety +1

      Local storage only applies to the current domain, so only your website.

  • @kawcco
    @kawcco Před 4 lety +2

    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  Před 4 lety

      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 Před rokem

    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.

  • @ramanasketches
    @ramanasketches Před 4 měsíci

    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

  • @Diablerick
    @Diablerick Před 2 lety +1

    I get a flash when I change pages on my site.
    Does anyone have solve this yet?

  • @DoctorMeatDoesHousecalls
    @DoctorMeatDoesHousecalls Před 6 měsíci

    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.

  • @neekowo
    @neekowo Před 2 lety

    6:05
    when i test the button, the console gave me an error "Uncaught TypeError: darkModeToggle is null"
    can anyone help please

  • @nimrodnorway3023
    @nimrodnorway3023 Před 2 lety

    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  Před 2 lety +1

      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).

  • @YPremSingha
    @YPremSingha Před 4 lety

    Awesome work,
    But why it's not working on my Safari ... 'QuotaExceededError'

  • @bintangnaufal
    @bintangnaufal Před rokem +1

    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 Před rokem

      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 :)))))

  • @nimrodnorway3023
    @nimrodnorway3023 Před 2 lety

    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  Před 2 lety +1

      That's true. I should have also used an aria-label on the button as well.

  • @vagg6078
    @vagg6078 Před 2 lety

    So I copied the code and saw that it didn't work but then i switched to css and it worked

  • @buivano3895
    @buivano3895 Před 3 lety

    good

  • @bytecodeman1
    @bytecodeman1 Před 4 lety +1

    Not too familiar with SVG. How do you generate that SVG code?

    • @pawpaaj
      @pawpaaj Před 4 lety +1

      For example you can export it from such programs as Adobe Illustrator.

  • @aqua-bery
    @aqua-bery Před 2 měsíci

    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

  • @sjspstudio9524
    @sjspstudio9524 Před 4 lety

    How to get localstorage value in asp.net code behind