To achieve this effect, CSS is more suitable than JavaScript.
In essence, you would design a div with the following styling:
<div id="overlay"></div>
<style>
#overlay{z-index:9999999;pointer-events:none;position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0.3);}
</style>
This code will generate a div that overlays your page content and darkens the entire page. (It's important to set the z-index of your overlay higher than other elements on the page, as different elements may have varying z-index values.)
Remember, the "a" value in rgba()
represents opacity - a value of 0.3
allows seeing what lies beneath, colored black by the first three values 0,0,0
.
If you were to accomplish this using only JavaScript, you can refer to this brief video demonstrating how to create HTML elements and add them to a page dynamically:
https://www.youtube.com/watch?v=VsXCK_2DJzA
A Challenge Arises (RESOLVED BELOW)
However, since the overlay div covers the page content, users might no longer interact with the content (i.e., cannot click fields or buttons). This is due to the elevated z-index placing the overlay between the cursor and the content. Every click registers on the overlay.
The solution, suggested by David Bailey in the comments, involves utilizing the css attribute pointer-events: none;
on the overlay div. This instruction prompts CSS to disregard any clicks on the element and let them pass through to the underlying components.
/* Note: this is NOT jQuery - look carefully. */
const $ = document.querySelector.bind(document);
$('#mybutt').addEventListener("click", function() {
alert("You clicked me");
});
$('#mybutt2').addEventListener("click", function() {
$('#mybutt2').innerText = 'Try clicking buttons NOW';
$('#olay').classList.add("noPtrEvts");
});
#olay{
pointer-events: none;
z-index:9999999;
position:fixed;
top:0;
left:0;
width:100vw;
height:100vh;
background:rgba(0,0,0,0.3);
}
.noPtrEvts{
pointer-events: auto !important;
}
<div id="olay"></div>
<h1>An Example Webpage</h1>
<div><img src="http://placekitten.com/300/150" /></div>
<button id="mybutt">Click me First</button>
<button id="mybutt2">Remove pointer-events CSS</button>