Creating onclick image overlay

Viewed 10723

What I have: I currently have code so where if you hover over an image, the overlay will slide from bottom to top.

What I want: I want to be able to achieve the same overlay slide from bottom to top with onclick instead of hover. I'm having trouble figuring out how to achieve this.

Code:

.container {
  position: relative;
  width: 50%;
}

.image {
  display: block;
  width: 100%;
  height: auto;
}

.overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #008CBA;
  overflow: hidden;
  width: 100%;
  height: 0;
  transition: .5s ease;
}

.container:hover .overlay {
  height: 100%;
}

.text {
  white-space: nowrap; 
  color: white;
  font-size: 20px;
  position: absolute;
  overflow: hidden;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
}
<!DOCTYPE html>
<html>
<head>

</head>
<body>

<h2>Slide in Overlay from the Bottom</h2>
<p>Hover over the image to see the effect.</p>

<div class="container">
  <img src="img_avatar.png" alt="Avatar" class="image">
  <div class="overlay">
    <div class="text">Hello World</div>
  </div>
</div>

</body>
</html>

6 Answers

If you have multiple images on your webpage you can use this snippet I created for my own project, all it does is to check if the element returns true on hover or null if it does not.

function isHover(e) {
    return (e.parentElement.querySelector(':hover') === e);
}
var myDiv = document.getElementById('container');
document.addEventListener('mousemove', function checkHover() {
    var hovered = isHover(myDiv);
    if (hovered !== checkHover.hovered) {
        hovered ? document.getElementById("overlay").style = "width: 100%;" : document.getElementById(
                "overlay").style =
            "";
    }
});
Related