Change div background color to percentage of height

I create a website with several divs for each other and a menu that adheres to the top. When you reach the new div, I want to change the background color of the menu. I already have this script;

$(document).ready(function(){ var scroll_pos = 0; $(document).scroll(function() { scroll_pos = $(this).scrollTop(); if(scroll_pos > 2280) { $("#menu").css('background-color', '#6FC6DF'); } else { $("#menu").css('background-color', '#B4B4B4'); } } ); $(document).scroll(function() { scroll_pos = $(this).scrollTop(); if(scroll_pos > 3220) { $("#menu").css('background-color', '#B4B4B4'); } }); 

This works fine, but now that I want the design to respond, I would like the background color to change by a percentage of the website. Is it possible?

Thanks!

0
source share
1 answer
 $(document).scroll(function() { var scroll_pos=$(document).scrollTop(); var docHeight=$(document).height(); var percent=(scroll_pos/docHeight); var red=Math.round(255*percent); $("body").css('background-color', 'rgba('+red+',0,0,1)'); } ); 

An example of how to make a document more red than the lower you scroll. You can also implement a function that maps percentages to the hex value you want to display :)

Or if you want to change depending on the percentage:

 $(document).scroll(function() { var scroll_pos=$(document).scrollTop(); var docHeight=$(document).height(); var percent=Math.round((scroll_pos/docHeight)*100); if (percent>33) $("#menu").css('background-color', '#ff0000'); } ); 
+1
source

Source: https://habr.com/ru/post/1490836/


All Articles