Daniel Williams
Daniel Williams

Reputation: 2317

How to make a page "lights out" except for one element

I'm not really asking for help with my code, I'm more asking, how do you do this?

When you click my div, the screen goes black, but I want my div underneath to still show as normal, but the rest of the area to be blacked out.

function lightsout() {
  document.getElementById("lightsout").style.visibility = "visible";
}
<div style="width:100px;height:100px;border:2px solid blue" onclick="lightsout()">Click Me</div>

<div id="lightsout" style="position:fixed;top:0;left:0;width:100%;height:100%;background-color:black;visibility:hidden;">

Upvotes: 3

Views: 316

Answers (3)

andreas
andreas

Reputation: 16936

You can simply add z-indexes to your positioning. With giving the black area a lower z-index than your button but a higher z-index than the rest, you will have your effect.

Also it is recommended to not use inline styles, as your code becomes way more maintainable with styles and markup seperate.

function lightsout() {
  document.getElementById("lightsout").classList.toggle("visible");
}
.button {
  position: relative;
  z-index: 10;
  width: 100px;
  height: 100px;
  border: 2px solid blue;
  background: white;
}

#lightsout {
  position: fixed;
  z-index: 5;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: gray;
  visibility: hidden;
}
#lightsout.visible {
  visibility: visible
}
<div class="button" onclick="lightsout()">Click Me</div>
<div id="lightsout"></div>

Other elements are hidden.

Upvotes: 1

Aslam
Aslam

Reputation: 9680

You can use the box-shadow property to achieve this effect.

Updated the Code

function lightsout() {
  document.getElementById("maindiv").classList.toggle("visible");
}
.visible{
box-shadow: 0 0 0 10000px #000;
position: relative;
}

body{
color: red;
}
<div style="width:100px;height:100px;border:2px solid blue; color: #000;" onclick="lightsout()" id="maindiv">Click Me</div>

Other elements on the page will be hidden...

Upvotes: 5

GuaHsu
GuaHsu

Reputation: 319

you can use css,

z-index, and add divbox background-color like this :)

function lightsout() {
  document.getElementById("lightsout").style.visibility = "visible";
}
#lightsout{
  z-index: -1
}
<div style="width:100px;height:100px;border:2px solid blue;background-color:white;" onclick="lightsout()">Click Me</div>

<div id="lightsout" style="position:fixed;top:0;left:0;width:100%;height:100%;background-color:black;visibility:hidden;">http://stackoverflow.com/questions/42688925/how-to-make-a-page-lights-out-except-for-one-element#

Upvotes: 0

Related Questions