ohyeah ohyeah - 5 months ago 20
CSS Question

How do I translate an image based on its height?

I have a tall image, that's in a div that's not as tall. I want to show the whole image by translating it. This is what I have so far:

https://jsfiddle.net/swv0w0em/



document.addEventListener("mouseover", function(event) {
var element = event.target;
if (element.classList.contains("myImage") &&
element.naturalWidth < element.naturalHeight) {
element.className += " imageScroll";


//element.style.transform = "translate(0,-" + element.naturalHeight + ")";
//element.style.mozTransition = "translate(0,-" + element.naturalHeight + ")";
//element.style.msTransform = "translate(0,-" + element.naturalHeight + ")";
//element.style.oTransform = "translate(0,-" + element.naturalHeight + ")";
//element.style.webkitTransform = "translate(0,-" + element.naturalHeight + ")";
}
});
document.addEventListener("mouseout", function(event) {
var element = event.target;
if (element.classList.contains("myImage")) {
element.className = element.className.replace(
/(?:^|\s)imageScroll(?!\S)/g, ''
);
}
});

div {
height: 200px;
overflow: hidden;
background-color: red;
}
img {
-moz-transition: all 3s ease-in-out;
-o-transition: all 3s ease-in-out;
-webkit-transition: all 3s ease-in-out;
transition: all 3s ease-in-out;
}
.imageScroll {
-moz-transform: translate(0, -350px);
-ms-transform: translate(0, -350px);
-o-transform: translate(0, -350px);
-webkit-transform: translate(0, -350px);
transform: translate(0, -350px);
}

<div>
<img src="https://placeimg.com/300/800/any" class="myImage" alt="SomeImage">
</div>





However, I can't figure out how to translate with the image height. I want the scrolling to stop as soon as the bottom of the image is in view. I don't know how tall the image will be before, so I can't hardcode it in CSS. That why I tried setting the style in JavaScript, but that did not work for me (see the commented out code).

My question: how do I get the image to scroll all the way down on mouseover, and stop scrolling when the bottom of the image is reached? I can't scroll past the height either, or I'll get ugly white space. I'm trying to get this done in pure JavaScript, without jQuery. Who can help?

Answer

With pure CSS you can use percentage unit in the translate, then subtract the height of container using top offset (position absolute):

div {
  height: 200px;
  overflow: hidden;
  position: relative;
}

.myImage {
  transition: all 3s ease-in-out;
  display: block;
  position: absolute;
  top: 0; left: 0;
}

.myImage:hover {
  top: 100%;
  transform: translateY(-100%);
}
<div>
  <img src="https://placeimg.com/300/800/any" class="myImage" alt="SomeImage">
</div>

jsFiddle: https://jsfiddle.net/azizn/h37dLzgf/1/