0

I want to rewrite the following code so that it doesn't get the height of the <body>, but rather the height of the element I put the object in to carry out the function:

var img = document.getElementById("logo");
window.onscroll = function() {
var bodyHeight = parseInt(getComputedStyle(document.body).height, 10);
var scrollLimit = bodyHeight - window.innerHeight;
var scrollTop = document.body.scrollTop;
var scrollPCT = (scrollTop / (scrollLimit / 100)) / 100;
logo.style.top = bodyHeight * scrollPCT - logo.offsetHeight + "px";
};

How can I target, say an ID, instead of document.body? I tried the following but it didn't work at all:

var img = document.getElementById("logo");
window.onscroll = function() {
var body = document.getElementById("container");
var bodyHeight = parseInt(getComputedStyle(document.getElementById("container")).height, 10);
var scrollLimit = bodyHeight - window.innerHeight;
var scrollTop = document.getElementById("container").scrollTop;
var scrollPCT = (scrollTop / (scrollLimit / 100)) / 100;
logo.style.top = bodyHeight * scrollPCT - logo.offsetHeight + "px";
};

The desired effect involves a reverse scroll in which an image will move down as the user scrolls down, instead of up, like it normally does.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Hex1189
  • 21
  • 2
  • 6
  • Can you explain what's the desired effect you want to achieve? Show some HTML, CSS etc? It's hard to reproduce anything with the given JS and understand fully your question... Have you tried to inspect the returned value of `scrollPCT`? – Roko C. Buljan Oct 11 '14 at 13:59
  • @ Roko The desired effect involves a reverse scroll in which an image will move down as the user scrolls down, instead of up, like it normally does. Although the above code works for body, I just need to target for a specific element. – Hex1189 Oct 11 '14 at 14:30

1 Answers1

1

I guess the computed height does not work? Use the clientHeight property:

var bodyHeight = document.getElementById("container").clientHeight;

(or one of the other height properties)

Community
  • 1
  • 1
Tim Jansen
  • 3,330
  • 2
  • 23
  • 28