Detecting whether a browser is capable of supporting dark mode

One method to determine if dark mode is active is by using prefers-color-scheme: dark:

const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;

Is there a way to detect if a browser supports dark mode as well? (By "supports dark mode" I mean when the browser automatically changes the default background/text colors of web pages).

To enforce dark mode in CSS, we can use:

color-scheme: dark;

However, some browsers like Firefox for Android might not acknowledge this. Hence, it would be ideal to hide theme selection if dark mode is unavailable.

Answer №1

One method I am currently using involves toggling between dark and light modes to see if the default color changes:

const hasDarkMode = function()
{
  const el = document.createElement("div");
  el.style.display = "none";
  document.body.appendChild(el);
  let color;
  /*canvastext - doesn't work in Samsung Internet, initial/unset - doesn't work in Firefox*/
  for(let i = 0, c = ["canvastext", "initial", "unset"]; i < c.length; i++ )
  {
    el.style.color = c[i];
    el.style.colorScheme = "dark";
    color = getComputedStyle(el).color;
    el.style.colorScheme = "light";
    color = color != getComputedStyle(el).color;
    if (color)
      break;
  }
  document.body.removeChild(el);
  return color;
}();

console.log("Dark mode supported:", hasDarkMode);

While this approach may not be the most elegant, it appears to be effective.

We can also explore another method suggested by @connexo:

const hasDarkMode = CSS.supports("color-scheme", "dark");

console.log("Dark mode supported:", hasDarkMode);
@supports (color-scheme: dark)
{
  .no-dark-mode
  {
    display: none;
  }
}
<div>Dark mode is <span class="no-dark-mode">not </span>available</div>

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

Creating a new row with a dropdown list upon clicking a button

I want to include a Textbox and dropdown list in a new row every time I click a button. However, I seem to be having trouble with this process. Can someone assist me in solving this issue? Thank you in advance. HTML <table> <tr> ...

Can you explain the meaning of this AJAX code snippet?

I've been researching online for information, but I'm struggling to find any details about the AJAX code snippet that I'm using: function getEmployeeFilterOptions(){ var opts = []; $checkboxes.each(function(){ if(this.checke ...

Error message in Material-UI TextField not displaying when state is updated using Object.assign technique

Currently, I am facing an issue with validating a login form and displaying errors dynamically. These errors are passed as props from the child component. The problem arises when I set the errors object using Object.assign - the errorText does not show up ...

What is the best way to arrange an array to display country data based on Covid cases in descending order rather than alphabetical order?

This particular code snippet retrieves Covid19 statistics data using an API. Currently, it displays the data for covid cases of all countries in Alphabetical order. However, I am looking to present the data in descending order, meaning that the country wit ...

Express: utilizing rawBody or buffer for a specific endpoint

I am looking to access the rawBody (buffer) specifically for a POST request on one route within my application. Currently, I have the following code snippet in my app.js: app.use(bodyParser.json({ verify: function(req, res, buf) { req.rawBody = buf; }})) ...

Fill a dropdown menu with options from a JSON object, arranging them in ascending order

I have a JSON hash that I am using to populate a combo box with the following code: $.each(json_hash, function(key, value) { $("#select").append("<option value='" + key + "'>" + value + "</option>"); }); The functionality w ...

The order of CSS precedence shifts even when the class sequence is the same

In my development setup, I have a react component that is embedded within two distinct applications each with their own webpack configurations. Within the component, I am utilizing a FontAwesome icon using the react-fontawesome library: <FontAwesom ...

If the text is too lengthy, enclose it within a div element

I am facing an issue with a fixed width DIV of 300px. Within this DIV, I have dynamic text that sometimes exceeds the width and gets cut off. Is there a way to make the text wrap when it exceeds the 300px limit without increasing the height of the DIV? Is ...

Having trouble clicking the button due to the overlay blocking it?

This code contains the HTML portion <li id="nav1" class="navs"><a unselectable="on" draggable="false" class="Navigation" href="http://youtube.com">YouTube</a></li> Below is the CSS code .navs:after { content: ""; position: ab ...

What is the best way to align the items in two lists at the center as if they were all individual

Q: How can I center the list-item elements of two unordered lists as if they were children of just one list? Example: {[1][1][1][1][2][2]} { [2][2] } CSS Alignment Challenge <div> <ul> &l ...

Unable to set selected property in React Material-UI menu item

One issue I'm facing is setting the selected prop using react mui menu item. In a multiple select menu list, there's a field called allValues that, when clicked, should toggle the selection of all menu items. The code for this functionality looks ...

Utilize Angular service to deliver on a promise

Currently, I have a service that is responsible for updating a value on the database. My goal is to update the view scope based on the result of this operation (whether it was successful or not). However, due to the asynchronous nature of the HTTP request ...

Unique alphanumeric code following the inclusion of a JavaScript file

I'm encountering an issue with a webpage that incorporates two JavaScript files. When inspecting it using firebug, I noticed that every time the page loads, these two files are included with the prefix ?_=someRandomNumber I'm unsure about the or ...

What is the best way to access the front camera on both Android and iOS devices in order to capture a photo using Vue.J

I am currently developing a PWA Vue.Js application and I am trying to implement a feature that allows users to take a picture with the front camera on their mobile devices. Although I have managed to write code that works on my desktop browser, I have bee ...

How to Use PHP to Submit Form Information

I am a beginner in PHP and I need help with sending form details to an email address. I have tried looking for solutions online but I keep running into the same issue - when I submit the form, it downloads the PHP file instead of sending an email. Below i ...

CSS for mobile devices not loading until the device is rotated

My website, redkrypt.com, is functioning perfectly on my laptop. However, I am facing an issue where the css file will only load on my iPhone 4S after I rotate it once. Once I do this, the website works both vertically and horizontally. I have tried variou ...

Tips on concealing modal popup when the page refreshes successfully

I implemented a progress modal popup to show progress for page reloads. This script is set to the master page and injects the progress modal popup when the form submit event is fired: <script type="text/javascript"> function ...

Find the sum of values in an array of objects if they are identical

[{ingName: "milk", quantity: "1.5", unit: "cups"}, {ingName: "sugar", quantity: "0.25", unit: "cups"}, {ingName: "vanilla extract", quantity: "1.0", unit: "tsp&quo ...

"Utilizing JQuery to enhance task management by implementing a delete function

I need help figuring out how to create a function that can delete tasks from my todo list. Currently, each task has its own remove button, but I want to implement a single remove button at the bottom that removes checked or crossed out tasks. Any suggestio ...

Tips on adjusting the pixel dimensions of an image using a file object

Within a form on our website, users have the ability to upload an image file. To ensure quality control, I've set up validation to confirm that the uploaded file is either an image or gif format. In addition to this, I'm looking for a solution th ...