Key Elements


Simple Darkmode with CSS & jQuery

Simple Darkmode with CSS & jQuery

This article aims to provide a simple solution to adding darkmode to your Elementor powered site by using CSS & jQuery. You don’t necessarily need to have pro for this to work but you will need an additional plugin to add your jQuery if your theme doesn’t supply an option for you to do so.

Here is what we will be accomplishing today.

A little Knowledge

Before we get too far ahead I want to explain how we this will work and what we will be targeting. We are going to use jQuery to affect the color of the body background as well as any p tags, h1, h2, h3 and links by simply adding a class to change their appearance when our button is clicked.

Our button will then change from a sun to a moon to let the user know that they are in darkmode.

There is a downside to this method which may be included later. Because this is not cookie based the browser will not remember the current state and if the user leaves or visit another page they will have to toggle it back on again.

Let’s Begin

You can put this button/link anywhere you like but for this example I will be adding it to my header by adding a html widget to the far right and adding this html.

<a class="dark"  href="#darkmode">
    <i class="fas fa-sun"></i>

Next we need to include the CSS now depending on your preference you can apply this css to your stylesheet or customizer.

.dark-bg {
	background: #1c1c1e;
	transition: all 0.5s ease;
	color: #fefefe!important;
	transition: all 0.5s ease;

This above css will control the colors of your background and text.

The jQuery

Here is the jQuery that will do all the work.

jQuery(document).ready(function( $ ){
   $("p, a, h2, h3").toggleClass("light-text");
  $(this).find('i').toggleClass('fas fa-sun fas fa-moon') 

So basically what the above script does is wait for the button with the class of .dark once a click has been initiated if will search for certain tags and also the body element.

It will then attach the classes light-text and dark-bg and apply those styles.

The last thing it will do is swap out the sun icon for the moon icon each time it is clicked.

Where to put the jQuery

I am very fond of this plugin Simple Custom CSS & JS I use it a-lot.

Your theme may offer a better method or you can simple go with script tags inside an html widget. I will be using the plugin mention above.

Go to custom CSS & JS > add custom js.

Give your script a name and copy and paste the script into the box.

Visit your site on the front end and try out your new darkmode trigger.

Keep in mind this is the first iteration of this script as time goes on and readers request and modify the script it will change.

Important Notice: Custom sections that have a custom background color are not affected by the trigger. The trigger only effects the body background.

Enjoy 😀.

Leave a Reply