I have multiple divs with images inside. I want to apply the parallax to the image inside the div. However, if I set the parallax scroll to the images, the images at the bottom of the screen make a white space inside the div since images scroll up to high.
This is my code so far.
HTML
<div class="workImg">
<img class="inWorkImg" src="img/08.png"/>
</div>
<div class="workImg">
<img class="inWorkImg" src="img/09.png"/>
</div>
<div class="workImg">
<img class="inWorkImg" src="img/10.png"/>
</div>
<div class="workImg">
<img class="inWorkImg" src="img/11.png"/>
</div>
CSS
.workImg{
position: absolute;
width: 80%;
height: 230px;
bottom: 15px;
overflow: hidden;
}
.inWorkImg {
object-fit: cover;
height: 110%;
}
JQUERY
var parallaxElements = $('.inWorkImg'),
parallaxQuantity = parallaxElements.length;
var visible = isInViewport(this)
$(window).on('scroll', function () {
if(visible) {
window.requestAnimationFrame(function () {
for (var i = 0; i < parallaxQuantity; i++) {
var currentElement = parallaxElements.eq(i);
var scrolled = $(window).scrollTop();
currentElement.css({
'transform': 'translate3d(0,' + scrolled * -0.06 + 'px, 0)'
});
}
});
}
});
Actually you don't have to use jQuery for that, but use pure css like that -
Instead of img
tag, those divs will get an background-image
property.
<div class="workImg1"></div>
<div class="workImg2"></div>
<div class="workImg3"></div>
<div class="workImg4"></div>
And CSS will look like that -
.workImg1, .workImg2, .workImg3, .workImg4 {
/* Set a specific height */
min-height: 500px;
/* Create the parallax scrolling effect */
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.workImg1 {
/* The image used */
background-image: url("IMG_URL");
}
.workImg2 {
/* The image used */
background-image: url("IMG_URL");
}
.workImg3 {
/* The image used */
background-image: url("IMG_URL");
}
.workImg4 {
/* The image used */
background-image: url("IMG_URL");
}