Javascript DOM Image overlay

Description

Javascript DOM Image overlay

View in separate window


<!DOCTYPE html>
<head>
<title>Overlay</title>
<style>
img/*w  w w  . j  a  v  a2s .  c o  m*/
{
  padding: 5px;
}

#outer
{
  width: 100%; height: 100%;
}
.overlay
{
   background-color: #000;
   opacity: .7;
   filter: alpha(opacity=70);
   position: fixed; top: 0; left: 0;
   width: 100%; height: 100%;
   z-index: 10;
}

.overlayimg
{
  position: absolute;
  z-index: 11;
  left: 50px;
  top: 50px;
}
</style>
<script>

function expandPhoto() {

   let overlay = document.createElement("div");
   overlay.setAttribute("id","overlay");
   overlay.setAttribute("class", "overlay"); 

   document.body.appendChild(overlay);   

   let img = document.createElement("img");
   img.setAttribute("id","img");
   img.src = this.getAttribute("data-larger");

   img.setAttribute("class","overlayimg");

   img.onclick=restore;

   document.body.appendChild(img);
}

function restore() {

 document.body.removeChild(document.getElementById("overlay")); 
 document.body.removeChild(document.getElementById("img"));
}
           

window.onload=function() {
   let imgs = document.getElementsByTagName("img");
   imgs[0].focus();
   for (let i = 0; i < imgs.length; i++) {
     imgs[i].onclick=expandPhoto;
     imgs[i].onkeydown=expandPhoto;
   }
}
  
</script>

</head>
<body>
<div id="outer">
  <p>Mouse click on image to expand the photo. To close expanded photo, mouse click on image.</p>
  <img src="image1.png" data-larger="image2.png" alt="circle" />
  <img src="image3.png" data-larger="image4.png" alt="arrow" />
  <img src="image5.png" data-larger="image6.png" alt="circle" />
  <img src="image7.png" data-larger="image8.png" alt="arrow" />
</div>
</body>
</html>



PreviousNext

Related