"Glowing orbs in the night: a dark mode spectacle with

I have implemented a night mode (or perhaps dark mode) toggle button located at the top-right corner of my webpage.

Here is a link to a perfect example showcasing what I am aiming for

However, unlike the provided link, I switch between night mode and light mode using the following code:

HTML I utilize a data-theme attribute to toggle between modes. (switching from night to light or light to night)

<body data-theme="">
    <div class="toggle" id="switch" onclick="toggleDarkMode()"></div>
</body>

JS

function toggleDarkMode() {
    var dataTheme = $('body').attr('data-theme');
    
    if(dataTheme == 'dark') {   
        $('body').attr('data-theme', 'light');
    } else {
        $('body').attr('data-theme', 'dark');
    }
};

I would appreciate any advice on how to implement a night mode toggle with an expanding circle animation using keyframes.
Thank you in advance!

Answer №1

An efficient approach to implementing a dark mode is to define a CSS class named dark, which contains all the necessary styles for dark mode. Then, you can toggle the presence of this class on your webpage by using an event listener.

document.querySelector('.toggle').addEventListener('click', function(e) {
  var body = document.getElementsByTagName('body')[0];
  body.className = body.className !== 'dark' ? 'dark' : '';
})
.dark {
  background: black;
  color: white;
}
<body>
  <p>Hello world</p>
  <button class='toggle'>Dark Mode</button>
</body>

Answer №2

To customize the styling of the body element based on a specific attribute, you can utilize a CSS attribute selector targeted at the data-theme attribute.

function switchTheme() {
  var theme = $('body').attr('data-theme');

  if (theme == 'dark') {
    $('body').attr('data-theme', 'light');
  } else {
    $('body').attr('data-theme', 'dark');
  }
};
body[data-theme="light"] {
  background-color: white;
  color: black;
}

body[data-theme="dark"] {
  background-color: black;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body data-theme="light">
  <p>Hello world</p>
  <button class="toggle" id="switch" onclick="switchTheme()">Switch Theme</button>
</body>

This approach enables you to apply various CSS styles as needed, including those referenced in your initial query.

Answer №3

Give this method a try

<script>
$(document).ready(function(){
  $("#toggle").click(function(){
       var theme = $('body').attr('data-theme');
       if(theme == 'dark') {   
           $('body').attr('data-theme', 'light');
       } else {
           $('body').attr('data-theme', 'dark');
       }
     };
});
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Please consider opening in a new tab rather than a new window

<a href='#' onclick="loadpage();">[RANDOM PAGE]</a> Whenever this code is clicked, the following function gets executed. function loadpage(){ $.ajax ({ type: "POST", url: "fetchpage.php", data: "showpage=1", success: function(msg) { ...

Adjust the size of every card in a row when one card is resized

At the top of the page, I have four cards that are visible. Each card's height adjusts based on its content and will resize when the window size is changed. My goal is to ensure that all cards in the same row have equal heights. To see a demo, visit: ...

Vue select is causing the selected choice of another selector to be influenced

Currently, I am facing an issue with a table displaying a specific Nova resource. The problem lies in the selectors within each row of the table - when one selector is changed, all other selectors automatically mirror that change. This behavior seems to be ...

What is the best way to access a video stored in a local file on the initial page and then watch it on the subsequent

I recently encountered a scenario where I needed to select a video on one page and have it automatically play on another page without any redirection. The initial page displays a list of videos for selection, like this: FirstPage Once a video is chosen on ...

Refreshing Vue by reloading new components and injecting them into the HTMLDOM

Is there a way to make Vue re-initialize itself after inserting a component fetched from an API into the DOM? The component looks like this: <div><My_component /></div> This component is part of a back-end snippet. When inserting it i ...

Hiding the SVG element with pattern definitions using the 'display: none' property makes the patterns completely disappear from view

When I include a set of SVG definitions at the top of my body, I encounter an issue where the svg tag with zero height and width creates unnecessary space at the beginning of the document. To resolve this, I initially use display:none, but this leads to pr ...

Error: Trying to access properties of an undefined object (specifically 'promise.data.map')

Currently, I am in the process of writing unit tests for a project built with Angular version 1.2. For my controller tests, I have set up a mockService that returns a deferred promise. One of the service methods looks like this: function getItems() { ...

How to include a file within another file in Node.js

When including one JavaScript file into another, I typically use the following syntax: var userControllerObj = require("../controller/userController"), userController = new userControllerObj.UserGatewayController(); I'm curious if I can u ...

Error: An issue occurred with the tasks in the Gruntfile.js file

pm WARN EPACKAGEJSON <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74041506001a1106041b0600151834445a445a44">[email protected]</a> No description npm WARN EPACKAGEJSON <a href="/cdn-cgi/l/email-protection" ...

"The boundary of suspense was updated before completing hydration." This error occurs when utilizing suspense and dynamic import within Next.js

I am currently working on lazy loading a list of data using suspense and dynamic import in Nextjs. However, I encountered the following error: Error: This Suspense boundary received an update before it finished hydrating. This caused the boundary to switch ...

Position the image slider uniformly at the bottom using CSS (utilizing the Slick Carousel library)

I am utilizing the slick carousel library to create a unique and elegant slider. However, when using images with varying heights, I am encountering issues in aligning the images at the same bottom: https://i.stack.imgur.com/ab5s3.png Here is my code snip ...

CSS layout: The full-width header should align its left margin with the centered content-div

Can someone help me out with a solution to my problem? My page has a 1040px centered div for content, menu, and footer. I want the header image to align with the left margin of the content div and expand towards the right side for higher screen resolutio ...

The cart total variable in Vuejs is coming back as NaN

I'm currently in the process of creating a cart system using vuejs and I've encountered an issue where my total variable is displaying NaN instead of calculating the total price of all products. Below is the function responsible for calculating ...

Gulp encountered an issue - TypeError: When attempting to call the 'match' method, it was found to be undefined

Currently, I'm attempting to utilize Gulp alongside BrowserSync for a website that is being hosted on MAMP and proxied through localhost:8888. Unfortunately, upon running gulp, I encounter the following error: [17:38:48] Starting 'browser-sync& ...

Upgrading the entire document's content using jQuery

I am dealing with an ajax response that provides the complete HTML structure of a webpage, as shown below: <!DOCTYPE> <html> <head> <!-- head content --> </head> <body> <!-- body content --> </b ...

Calculating the combined total and mean values within an object using JavaScript

I have a set of data in the following format: { "Dates": ["January", "January", "March", "March", "March", "November", "November"], "Values": [45.6, 0.5, 59.3, 46.56, ...

"Step-by-Step Guide: Activating Tab Functionality in J

I'm facing an issue here - I've been attempting to log the event's key code and I keep getting key number (9). I believe my script isn't disabling event.keyCode properly, hence the key function remains active. What changes should I make ...

Positioning HTML elements using CSS and avoiding the use of tables

I'm struggling with my clear CSS declarations. This is how I'd like it to appear: View the Fiddle demo HTML: <div id="timesheeteditor"> <div id="weekselector"> <div>Week 1</div> <div>Week 2</div> ...

Ensure that the date range picker consistently shows dates in a sequential order

Currently utilizing the vuetify date range picker component https://i.stack.imgur.com/s5s19.png At this moment, it is showcasing https://i.stack.imgur.com/GgTgP.png I am looking to enforce a specific display format, always showing the lesser date first ...

Get the value of a CSS property in Python by parsing the rendered HTML

Currently, I am using Selenium and PhantomJS in conjunction with Python for the purpose of crawling rendered web pages. While it is a straightforward process to identify the presence of specific words within the HTML content (e.g. if "example" in html...), ...