NPLS
NPLS

Reputation: 531

dynamically change text color (as a linear gradient) based on page scroll

I'd like to dynamically change text color (as a linear gradient) based on page scroll position from top.

window.onscroll=function(){getPosition()}

function getPosition()
{
  var scrollPos = $(window).scrollTop();
  loggy(""+scrollPos,3);
}

the code above gives me the position from the top of the page. What I would like to do is to have a function that gives me back a color, and such color is based on a linear gradient that depends on the scrollPos value.

the linear gradient should start from rgb(201,69,109) to rgb(18,23,28) , and it has to "span" it from scrollPos=0 to scrollPos=1400

Is there a way to do this ?

function(scrollPos){
  var  color = f_color(scrollPos);
  return color;
}

EDIT : here How to get color value from gradient by percentage with javascript? I found this example that changes color from red to green. But I haven't succeeded in setting custom colors as mine

$('#elm').css({color: 'rgb(' + ((100 - percent) *2.56) +',' + (percent *2.56) +',0)'})

(100*scrollPos)/1400 with this as the percentage

Upvotes: 0

Views: 879

Answers (1)

rook218
rook218

Reputation: 672

First you'll want to find your RGB values that you want to scroll between. I'll assume you want to go between pure black and pure white with gray in between (0 to 255 in all three RGB values)

const text = document.querySelector('#id');
window.onscroll(function() {
    // gets your entire window height to scale to 255
    let colorVal = window.scrollHeight / (window.height / 255);

    text.style.color = "rgb(" + colorVal + "," + colorVal + "," + colorVal + ")";
}

Of course if you want something more subtle or beautiful you can play with the values in a function like this one.

Upvotes: 2

Related Questions