Last active
October 12, 2024 21:04
-
-
Save huzaifaasim017/16b123c200281564afb95bc37f8706c6 to your computer and use it in GitHub Desktop.
This code will add a darkmode class on darkmode turned on with the local storage, and will change the darkmode image using the the data attribute.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!-- Button HTML --> | |
| <div class="darkmode d-flex"> | |
| <p class="my-auto">Darkmode: </p> | |
| <div class="form-check form-switch ms-2 transform-icon"> | |
| <input data-text="Turn on or off dark mode" class="darkModeButton form-check-input shadow-none" type="checkbox" role="switch"> | |
| </div> | |
| </div> | |
| <!-- Image HTML --> | |
| <img data-original-src="your-path" data-dark-mode-src="your-path" src="your-path" alt="Inspire FM" class="img-fluid w-75 dark-mode-image" loading="eager" /> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //jQuery Code | |
| const toggleDarkMode = () => { | |
| const body = $('body'); | |
| const isDarkMode = !body.hasClass('dark-mode'); | |
| body.toggleClass('dark-mode', isDarkMode); | |
| localStorage.setItem('darkMode', isDarkMode); | |
| updateImages(isDarkMode); | |
| const darkModeButton = $('.darkModeButton'); | |
| darkModeButton.prop('checked', isDarkMode); | |
| // darkModeButton.toggleClass('fa-moon fa-sun'); | |
| }; | |
| const updateImages = (isDarkMode) => { | |
| const imagesToChange = $('.dark-mode-image'); | |
| imagesToChange.each((index, element) => { | |
| const darkModeSrc = $(element).data('dark-mode-src'); | |
| const newSrc = isDarkMode ? darkModeSrc : $(element).data('original-src'); | |
| $(element).attr('src', newSrc); | |
| }); | |
| }; | |
| const darkModePref = localStorage.getItem('darkMode'); | |
| if (darkModePref === 'true') { | |
| $('body').addClass('dark-mode'); | |
| updateImages(true); | |
| $('.darkModeButton').prop('checked', true); | |
| $('.darkModeButton').removeClass('fa-moon').addClass('fa-sun'); | |
| } | |
| $('.darkModeButton').on('click', toggleDarkMode); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment