darkmode js

Darkmode JS

Darkmode JS is a JavaScript library that allows you to add a dark mode toggle switch to your website or web application. It's a popular feature that's becoming more and more common in web design, as many users prefer to use dark mode to reduce eye strain and conserve battery life on their devices.

To use Darkmode JS, you first need to include the library in your project. You can do this by adding the following code to the <head> section of your HTML file:


<head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/darkmode-js.min.js"></script>
</head>

Basic Usage

Once you've included the library, you can add a dark mode toggle switch to your page by creating a new instance of the Darkmode class:


const options = {
  bottom: '64px', // default: '32px'
  right: 'unset', // default: '32px'
  left: '32px', // default: 'unset'
  time: '0.5s', // default: '0.3s'
  mixColor: '#fff', // default: '#fff'
  backgroundColor: '#fff', // default: '#fff'
  buttonColorDark: '#100f2c', // default: '#100f2c'
  buttonColorLight: '#fff', // default: '#fff'
  saveInCookies: true, // default: true,
  label: '🌓', // default: ''
  autoMatchOsTheme: true // default: true
}

const darkmode = new Darkmode(options);
darkmode.showWidget();

This will create a new instance of the Darkmode class with the specified options, and then call the showWidget method to display the dark mode toggle switch on your page.

Advanced Usage

If you want more control over how dark mode is applied to your page, you can use the toggle() method to manually toggle between light and dark mode:


const options = {
  mixColor: '#fff',
  backgroundColor: '#000',
  buttonColorDark: '#fff',
  buttonColorLight: '#000'
}

const darkmode = new Darkmode(options);

// Toggle to dark mode
darkmode.toggle();

// Toggle back to light mode
darkmode.toggle();

You can also use the isActivated() method to check whether dark mode is currently active on your page:


if (darkmode.isActivated()) {
  console.log('Dark mode is currently active.')
} else {
  console.log('Light mode is currently active.')
}

Conclusion

Darkmode JS is a powerful and easy-to-use JavaScript library that allows you to add a dark mode toggle switch to your website or web application. With just a few lines of code, you can give your users the option to switch between light and dark mode, improving the user experience and making your site more accessible.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe