Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Change tab bar color dynamically using JavaScript

In one of my applications called Notepad, I am using something called theme-color meta tag that can be used to change the color of the browser’s address bar (or tab bar in Safari).

You may like: Tab bar theming of Safari 15

This is a very handy meta tag that allows you to change the color of the address bar to match the color of your application.

<meta name="theme-color" content="#4d4d4d">

As you can tell, you need to specify the color of the address bar in the content attribute of the theme-color meta tag. And for my application, the color I’m using by default is #4d4d4d which matches the header color of the application when its light mode is activated.

But, I wanted to change the color of the address bar based on the theme of the application. So, I needed to change the color of the address bar dynamically when the user changes the theme of the application. i.e light or dark.

Here’s how I have implemented it.

As you can see, the top bar where it says “Notepad - Offline capable” represents the address bar and the color of it changes based on the theme of the application.

Here’s the code that I have used to change the color of the address bar.

const themeColor = document.querySelector('meta[name="theme-color"]');

function changeThemeColorMeta() {
    const isDarkTheme = window
                            .matchMedia('(prefers-color-scheme: dark)')
                            .matches;
                            
    const color = isDarkTheme ? '#0d1117' : '#4d4d4d';

    themeColor.setAttribute('content', color);
}

As you can tell, I have a themeColor variable that holds the reference to the meta tag. And then I have a changeThemeColorMeta function that changes the color of the address bar dynamically based on the current theme (i.e. dark or light) of the application using the setAttribute method.

And that’s pretty much it! This is how I have implemented it in my application. And it works like a charm.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?