I have a problem creating an overlay on click of a button, and re-clicking it will close the overlay.
<section>
<div class="col-md-12">
<section class="masthead">
<span class="button">This is a button</span>
</section>
You can create a <div>
with fixed position for your overlay. Add an onClickListener for your <span class="button">
that calls your toggleOverlay()
function. And change the opacity
of your overlay <div>
to hide/show it. Code example below:
function toggleOverlay() { let overlayDiv = document.querySelector(".overlay"); console.log(overlayDiv.style.opacity); if (overlayDiv.style.opacity === '0') overlayDiv.style.opacity = 1; else overlayDiv.style.opacity = 0; }
.overlay { position: fixed; width: 50%; text-align: center; background-color: red; border-radius: 10px; font-size: 20px; height: 30px; opacity: 0; transition: opacity .2s ease-out; }
<div class="overlay" style="opacity: 0;">Overlay</div> <br> <br> <br> <div> <button onclick="toggleOverlay()">Show/Hide Overlay</button> </div>
A solution for the problem:
Javascript:
function init() {
var btn = document.getElementById("overlayBtn");
var overlay = document.getElementById("overlay");
btn.addEventListener("click", function() {
addOverlay();
});
overlay.addEventListener("click", function() {
removeOverlay();
});
}
function addOverlay() {
var overlay = document.getElementById("overlay");
overlay.style.display = "block";
}
function removeOverlay() {
var overlay = document.getElementById("overlay");
overlay.style.display = "none";
}
window.onload = init;
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<main class="main">
<section class="masthead">
<button id="overlayBtn" class="button">This is a button</button>
</section>
<div class="overlay" id="overlay"></div>
</main>
</body>
</html>
CSS:
.main {
height: 100vh;
}
.overlay {
background: black;
opacity: 0.2;
height: 100vh;
width: 100vw;
position: fixed;
top: 0;
left: 0;
display: none;
}
Could be a start of creating an overlay. But there are many ways to do this. This is using a fixed div occupying the entire screen. Only showing it when it is toggled, and on click on the overlay will make it disappear again.
Working plunker: http://plnkr.co/edit/eG8fkhvMYnzAQP0SRPSc?p=preview
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.