megacolorboy

Abdush Shakoor's Weblog

Writings, experiments & ideas.

Dark/Light mode with CSS and JavaScript

A simple guide on how to implement a dark/light theme switcher with CSS and JavaScript

It's quite common these days that many websites let their users to decide their preferred color scheme(s). Giving this sort of customizability offers good user experience.

In this article, I'll provide a simple step-by-step guide on how to implement a dark/light theme switcher with HTML, CSS and JavaScript.

Prerequisites

This article assumes that the reader has a basic know-how on HTML, CSS, JavaScript and basic knowledge on using the command-line.

Using CSS variables

I always wanted to implement one for this website too and I thought of making use of CSS variables as I found it to be quite straight forward and I don't have to worry too much about browser support.

Try adding the below CSS to your stylesheet:

    :root {
        --background-color: white;
        --font-color: black;
        --accent-color: red;
        --alt-background-color: black;
        --alt-font-color: white;
        --alt-accent-color: yellow;
    }

    html {
        background-color: var(--background-color);
        color: var(--font-color);
    }

    a {
        color: var(--accent-color);
    }

    html[data-theme="dark"] {
        background-color: var(--alt-background-color);
        color: var(--alt-font-color);
    }

    html[data-theme="dark"] a {
        color: var(--alt-accent-color);
    }
   

The :root selector contains a set of default values and in this case, these are just different colors, kind of like how we initialize variables in other programming languages.

For example, whenever the data-theme attribute is set to dark, the default values will be overidden by the html[data-theme="dark"] CSS rule for the theme to take effect.

Really, it's that simple!

Add some markup

That depends on what you really want to have in your website but for this tutorial, you can just place a simple button somewhere in your navigation bar or anywhere you like:

<button class="themeSwitcher">Dark/Light</button>

Toggle between light and dark themes

Yes, we are getting there and you just have to write a simple logic that checks if whether the current theme is dark or light based on the class used on the <body> element.

$('.themeSwitcher').on('click', function(){
    switch($('body').attr('data-theme')){
        case "dark":
            $('body').attr('data-theme', 'dark');
            break;

        case "light":
        default:
            $('body').attr('data-theme', '');
            break;
    }
});

Save user's preference in their browser

If your button works as expected, good! Now, once you refresh the page, the background would return to it's default mode but that's not what we wanted, right?

But why does it return instead of staying dark? Because your "preference" is not stored in your browser.

Modify your code to store your preferences in your browser:

<script>
$('.themeSwitcher').on('click', function(){
    switch($('body').attr('data-theme')){
        case "dark":
            $('body').attr('data-theme', 'dark');
            localStorage.setItem("theme", "dark");
            break;

        case "light":
        default:
            $('body').attr('data-theme', '');
            localStorage.setItem("theme", "");
            break;
    }
});
</script>

This should work fine but you'll want to avoid the "flickering" issue while changing themes or refreshing the page, in order to do that, make sure that you check the user preference before the page is completely loaded:

<script>
    if(localStorage.theme){
        document.documentElement.setAttribute('data-theme', localStorage.getItem("theme"));
    }
</script>

Conclusion

Well, if you've noticed, I wrote a simple theme switcher for my blog too. Try it out and you can inspect the code to see how it works.

Hope you enjoyed this article!

Stay tuned for more!

View your wget progress even after closing your SSH session

Few days back, I ran a wget command to download a file and accidentally closed the SSH client.

I logged in again and checked the list of active processes and thankfully, the wget process was still running except that I wasn't able to know the current progress of it.

So, I did a little research and found a way to view the progress, so I tried the following command:

tail -f wget_log

And, I was able to view it's current download progress again.

Hope this helps you out!

How to use GitHub Personal Access Token to authenticate your git commits?

On November 2020, GitHub had announced that they would no longer accept basic username/password to authenticate git commits and it would be deprecated by Mid 2021.

Instead, they recommend you to authenticate your git commits using a Personal Access Token from your GitHub account.

Generate a personal access token

  1. Unset your credentials from your remote repository: git config --local --unset credential.helper
  2. Login to your GitHub account and go to Settings
  3. Then navigate to Developer Settings -> Personal Access Tokens
  4. Click on Generate new token
  5. Give a name to your Personal Access Token and the necessary permissions required.
  6. Once done, hit on Generate token
  7. The token will be shown once, so make sure to copy it and store it somewhere that you can remember.

Update your remote repository

Once you've generated a token, you just have to update your remote repository by following the below steps:

1. Update remote repository URL

git remote set-url origin https://<your_access_token>@github.com/<your_git_repo_url>

2. Just git pull once

Now, just perform git pull operation once and you should be good:

git pull https://<your_access_token>@github.com/<your_git_repo_url>

Hope this helps you out!

How to fetch a JSON object from an array of JSON objects by property value?

Say, for example, you have an array of JSON objects that contains the following data:

var arrOfObjects = [
    {
        name: "John Doe",
        age: 20,
        email: "john.doe@email.com"
    },
    {
        name: "Bob Smith",
        age: 56,
        email: "bob.smith@email.com"
    },
];

Hmm, that's pretty basic but how will get the information of "Bob Smith" using his email? Well, that's where the Array.find() method comes into the picture.

Try reading the Mozilla Documentation on Array.prototype.find() and implement the following:

var key = "email";
var valueToFind = "bob.smith@email.com";
var result = arrOfObjects.find(obj => {
    return obj[key] == value;
});

//This should give you the record of Bob Smith.
console.log(result) 

This works fine on all browsers except Internet Explorer (I mean, it sucks anyways!), which is okay!

Hope you found this useful!

How to update values of a column from one table to another?

Sometimes, I come across situations where I would need to update a newly added in a pivot table and this query does come in handy:

UPDATE table_a INNER JOIN table_b ON table_b.col_x = table_a.col_x SET table_a.col_y = table_b.col_y;

Hope you found this useful too!

How to switch between integrated terminal and editor in Visual Studio Code?

While, I'm trying to adjust myself to using Visual Studio Code, I found it quite annoying that there isn't a shortcut to switch focus between the editor and the integrated terminal. For a guy, like me, who makes use of the keyboard all the time, that's pretty important.

I did some research and found a way on how to do it. Just type Ctrl+Shift+P and type Open Keyboard Shortcuts and add these lines:

[
    {"key": "ctrl+`", "command":"workbench.action.terminal.focus"},
    {"key": "ctrl+`", "command":"workbench.action.focusActiveEditorGroup", "when": "terminalFocus"},
]

Save the file and now, you'll be able to switch between the two by pressing Ctrl+` keys.

Hope you found this tip useful!

Redirect from HTTP to HTTPS in Apache VirtualHosts

Here's a simple technique on how I learned to redirect a site from HTTP to HTTPS automatically using Apache's VirtualHost configuration.

Go to your configuration file or 000-default.conf and modify your configuration to something like this:

<VirtualHost *:80>
    ServerName your.domain.com
    Redirect permanent / https://your.domain.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName your.domain.com
    SSLEngine On
    # insert code here...
</VirtualHost>

Save the file and check if the configuration is correct before your restart the server:

sudo apachectl configtest

If you get the message, Syntax OK, then go ahead and restart the server:

sudo systemctl restart apache2

Now, your visitors will be redirected from HTTP to HTTPS automatically!

Hope you found this tip useful!

Quick Search for file in your workspace in Visual Studio Code

Recently, started using Visual Studio Code as I'm yet figure out a way to install Sublime Text on Void Linux (using it as my current daily driver).

I'm always used to looking for my files using keyboard shortcuts in Sublime Text and I was kind of surprised this feature isn't enabled by default in Visual Studio Code.

Anyway, after a little digging, I found out that adding this line to your settings.json file would allow you to look for files in your workspace:

"search.useIgnoreFiles": false

And, now try Ctrl+P and you'll be able to search for your file(s) easily.

Hope you found this tip useful!