How do I add a caption overlay to a photo on hover AND click?

232 views Asked by At

I'm trying to add a caption to a photo. I want the name to always appear underneath the photo, while I would like the caption to show up on hover AND when clicked (and stay visible until another click). Is this possible? I'm able to do the two actions separately, but not together.

My other option is to use hover on normal screens and the click option on mobile.

Here's what I'm working with:

<!DOCTYPE html>
<html>
<head>

<script   src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("img").click(function(){
$("p").toggle();
});
});

</script>

<style>
.container {
    position: relative;
    width: 400px;
}

.image {
  opacity: 1;
  display: block;
  width: 100%;
  height: auto;
  transition: .5s ease;
  backface-visibility: hidden;
}

.middle {
  transition: 0.5s ease;
  opacity: 0;
  width:100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%)
}

p   {
  background-color: none;
  font-family:sans-serif;
  font-style:italic;
  color: black;
  font-size: 14px;
  line-height:24px;
  padding: 12px 12px;
}

.container:hover  .image {
  opacity: 0.2;
}

.container:hover  .middle {
  opacity: 1;
}

.text p{
  background-color: none;
  font-family:sans-serif;
  font-style:italic;
  color: black;
  font-size: 14px;
  line-height:24px;
  text-align: center;
  padding: 12px 12px;
}
</style>
</head>

<body>

<div class="container">

  <img src="https://static1.squarespace.com/static/511526cde4b067782b69109c/517aa359e4b0ab81ac8d931c/517aa396e4b041a7f26623d5/1366991956677/05-corporate-headshot-photo-WBEZ+-+Chicago+Public+Media_Edwards_Steve_Programming_120328_1210.psd.JPG-1500px.JPG" alt="Avatar" class="image" style="width:100%">

    <div class="middle">

    <p class="text">Rodney Erickson is a content marketing professional at HubSpot, an inbound marketing and sales platform that helps companies attract visitors, convert leads, and close customers. Previously, Rodney worked as a marketing manager for a tech software startup. He graduated with honors from Columbia University with a dual degree in Business Administration and Creative Writing."</p>

    </div>

    <p>RODNEY ERICKSON, M.B.A.<br>Content Marketing</p>

    </div>  

</body>
</html>

Thanks :)

1

There are 1 answers

0
nibnut On

Sure, so instead of using javascript to toggle your caption itself on click, I'd use javascript to toggle a class on your container.

Then in CSS, you can make sure that when the container is hovered over, OR when it has that special class, both situation show the caption. Any other time, your caption would be hidden.

Hope this helps!