Use JavaScript to add night mode to web pages

Xiaochen Wang
Nov 17, 2018 · 2 min read

I had to add change web page brightness to the Seneca Blackboard Chrome Extension for my third Pull Request in Release 0.3 assignment. I have use my JavaScript code experience to add this new feature.

How it works?

press Alt+Z: open dark mode,
Alt+X: close mode,
Alt+↑: increase brightness,
Alt+↓: decrease brightness

This new feature effect is looks like down below these tow pictures:

Image for post
Image for post
Image for post
Image for post

First, I created a new .js file to write my code and create a function to change the css style:

function cover(brightness) {                                                  if (typeof(div) == 'undefined') {                                                    div = document.createElement('div');                                                    div.setAttribute('style', 'position:fixed;top:0;left:0;outline:5000px solid;z-index:99999;');                                                    document.body.appendChild(div);                                                } else {                                                      div.style.display = '';                                                }                                                div.style.outlineColor = 'rgba(0,0,0,' + brightness + ')';                                            }

And I add an event listener to user active for the website.

window.addEventListener('keydown', function(e) {                                                if (e.altKey && e.keyCode == 90) { 
//Alt+Z: open dark mode cover(brightness = 0.3); }
if (e.altKey && e.keyCode == 88) {
//Alt+X:close mode cover(brightness = 0); }
if (e.altKey && e.keyCode == 38) {
//Alt+↑: increase brigtness if (brightness - 0.05 > 0.05) cover(brightness -= 0.05); }
if (e.altKey && e.keyCode == 40) {
//Alt+↓: decrease brigtness if (brightness + 0.05 < 0.95) cover(brightness += 0.05); }
}, false);

Issue: https://github.com/yevseytsev/SenecaBlackboardExtension/issues/82

Pull Request: https://github.com/yevseytsev/SenecaBlackboardExtension/pull/83

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store