RhysE96
RhysE96

Reputation: 197

Changing the position of div on scroll

I want an image to scroll up as I scroll down the page. I could do that quite easily, but the issue I'm having is that in the jQuery I'm changing the image's CSS, specifically its transform property. But I'm using the transform property already, to center align the image.

Code:

.planeImg {
    position: absolute;
    display: block;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: url("../images/plane.png");
    background-size: contain;
    background-repeat: no-repeat;
    z-index: 99;
    height: 80px;
    width: 300px;
}

$(window).on("scroll", function() {
    var wScroll = $(this).scrollTop();
    $('.planeImg').css({'transform' : 'translate(0px, -'+ wScroll /2 +'%)'})
});

So because I'm using the transform property to center align the image, the jQuery is buggering up the position of my image.

Upvotes: 0

Views: 6559

Answers (1)

user286089
user286089

Reputation: 172

I changed the calculation of wScroll to make the scrolling of the image follow the scrolling of the page. Please, let me know if this helps.

Fiddle

javascript

$(window).on("scroll", function() {
  var wScroll = ($(this).scrollTop() / $(window).height()) + 50;
  $('.planeImg').css({
    'transform': 'translate(-50%, -' + (wScroll) + '%)'
  })
});

CSS

.planeImg {
  position: absolute;
  display: block;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background: url("https://www.google.be/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
  background-size: contain;
  background-repeat: no-repeat;
  z-index: 99;
  height: 80px;
  width: 300px;
}

Upvotes: 1

Related Questions