0

I want an image inside div to be moving vertically down whenever a user scrolls. It has to end only at the end of the page. Have used the below script solution from the another post, however it doesn`t help.

HTML

<div id="wrapper">
   <img src="images/samp_scroll.png" class="ïmage">
</div>

CSS:

#wrapper {
    position: absolute;
}
.image {
    width: 560px;
    height: 700px;
}

Script:

window.onscroll = function (e) {
  var vertical_position = 0;
  if (pageYOffset)//usual
    vertical_position = pageYOffset;
  else if (document.documentElement.clientHeight)//ie
    vertical_position = document.documentElement.scrollTop;
  else if (document.body)//ie quirks
    vertical_position = document.body.scrollTop;
console.log( vertical_position);
  var your_div = document.getElementById('wrapper');
  your_div.top = (vertical_position + 200) + 'px';//200 is arbitrary.. just to show you could now position it how you want
}

What is that I am doing wrong here?? Verfying this further, though I could get the console value vertical_position I can`t really move the div using the below code.

var your_div = document.getElementById("wrapper"); your_div.top = 400 + 'px';

Is there any other best way to deal with Moving html elements with DIV? Any articles which explains? I am really new to this. Please help me out.

Adding style before the top, worked. However looks like the style applies only once as it moves only once as I scroll. Any ideas.

Ashwin
  • 483
  • 1
  • 9
  • 25

2 Answers2

1

One small miss, it should be style.top:

your_div.style.top = (vertical_position + 200) + 'px';
Vijay Dev
  • 1,024
  • 7
  • 14
  • Thanks that did work. What if if I want my div to move along with the scroll. Looks like this only moves once!! – Ashwin Nov 16 '15 at 07:31
  • Try moving the these code `var your_div = document.getElementById('wrapper'); your_div.top = (vertical_position + 200) + 'px';` after and outside the `else if`. Currently `top` value only gets updated when that `else if` is true. – Vijay Dev Nov 16 '15 at 07:55
  • Is it? But I see my console.log gets frequently updated every time I scroll. Unlikely this will be issue right? – Ashwin Nov 16 '15 at 08:21
0

Replace

var your_div = document.getElementById('wrapper');
your_div.top = (vertical_position + 200) + 'px';//200 is arbitrary.. just to show you could now position it how you want

with

$("#wrapper").css("top",(vertical_position + 200) + 'px');