Green Ball
Green Ball

Reputation: 90

Invert color of a page

I'm making a script to invert color of a HTML page. So it is easier to look at at night. I'm using filter: invert(100%) to do it.

Here is the script:

document.body.style.filter = "invert(100%)";
Object.values(document.body.getElementsByTagName("*")).forEach(e => {
    e.style.filter = "invert(100%)"
});

However it didn't really work.

Inverted

The Stack Overflow logo on the header is gone, as well as the buttons. What did I do wrong, and is there a better method than this?

Thanks in advance.

Upvotes: 2

Views: 2277

Answers (1)

Richard
Richard

Reputation: 7433

Your solution:

document.body.style.filter = "invert(100%)";
Object.values(document.body.getElementsByTagName("*")).forEach(e => {
    e.style.filter = "invert(100%)"
});

didn't really work because you're inverting colours from parent elements and their children. Inverting twice causes the element to have the original colour. Therefore, you only need to invert the colour of the parent(s) (in this case, the html, which is the root of everything):

document.querySelector('html').style.filter = 'invert(100%)'

And every colour will be inverted. Note that if you try to use this on a colourless element, nothing will change, i.e. if you try this script on this page, you will notice that the div on the left side of this page with the id left-sidebar will not change in colour. This is due to the sidebar not having any colour (the middle section and right sidebar is inverted because they're inside the div#content which has white background colour).

However, if you add background (e.g. white) to the left side bar, it will also invert its colour.

Upvotes: 3

Related Questions