Harry Day
Harry Day

Reputation: 408

Scroll Effect doesn't work on chrome

I have a scroll effect that changes the colour of the background by finding the users position on the page and using that to set the colour. This works fine on safari and in Atom Html Previewer however when I checked it on chrome it didn't work. My website is harry-day.con

Any suggestions on why it doesn't work or how to fix it? I tried modifying the JS slightly but nothing worked.

Here is the JavaScript I am using:

function scroll(){
    var body = document.body,
    html = document.documentElement;
    var height = html.scrollHeight - html.clientHeight;
    var color = Math.round((body.scrollTop / height) * 255);
    body.style.backgroundColor = "rgb("+color+","+color+","+color+")";
}

Edit: I tried using var color = Math.round((html.scrollTop / height) * 255); however now it does not work when I tested it locally in Safari.

Upvotes: 1

Views: 279

Answers (1)

Amr Noman
Amr Noman

Reputation: 2637

You can check this for a cross-browser way of getting current scroll position:

var doc = document.documentElement;
var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

function scroll(){
    var body = document.body;
    var doc = document.documentElement;
    var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
    var height = doc.scrollHeight - doc.clientHeight;
    var color = Math.round((top / height) * 255);
    body.style.backgroundColor = "rgb("+color+","+color+","+color+")";
}

window.addEventListener('scroll', scroll);
body {
  height: 1400px;
}

Upvotes: 3

Related Questions