3

I want to change the background-color when the user is scrolling down the page, so it should change on section change? I've searched and yet not found the answer.

// When on particular section change body background-color 
const sectionOne = document.getElementById('section-1');
const sectionTwo = document.getElementById('section-2');
const sectionThree = document.getElementById('section-3');
const sectionFour = document.getElementById('section-4');

if(sectionOne) {
        document.body.style.backgroundColor = "#118AB2";   
    } else if (sectionTwo) {
        document.body.style.backgroundColor = "#06D6A0"; 
    } else if (sectionThree) {
        document.body.style.backgroundColor = "#FFD166"; 
    } else {
        document.body.style.backgroundColor = "#073B4C"; 
    }
section {
  height: 100vh;
}
<section id="section-1">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-2">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-3">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-4">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30
Becky B
  • 65
  • 6
  • 1
    Although it might be considered over-engineering, you can use [Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API). However, if your sections always fill the entire page, the easiest solution would be using CSS and adding the background to the section itself. – Farsad Nov 01 '20 at 09:22

3 Answers3

1

There are a number of ways to do this. I would move to something more dynamic like this sample code.

Basically, the colour is moved to a data attribute the <section>.

You could restrict the colour change to just the paragraph instead of the entire page.

The sample code is using mouseover, but this might not be suitable for you.

function updateBG(e) {
  document.body.style.background = this.getAttribute("data");
}
window.onload = function(){
  var d = document.querySelectorAll("section[data]");
  if (d) {
    var i, max = d.length;
    for(i=0;i<max;i++) {
      d[i].addEventListener("mouseover",updateBG,false);
    }
  }
}
<section data="#118AB2">
<p>Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked.</p>
</section>
<section data="#06D6A0">
<p>Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked.</p>
</section>
<section data="#FFD166">
<p>Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked.</p>
</section>
<section data="#073B4C">
<p>Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked.</p>
</section>
Tigger
  • 8,980
  • 5
  • 36
  • 40
1

Here is my solution using jquery.

$(document).scroll(function(event) {
  if ($(this).scrollTop() >= ($('#section-1').position().top - 100)) {
    $('body').css('background-color', '#118AB2');
  }
  if ($(this).scrollTop() >= ($('#section-2').position().top - 100)) {
    $('body').css('background-color', '#06D6A0');
  }
  if ($(this).scrollTop() >= ($('#section-3').position().top - 100)) {
    $('body').css('background-color', '#FFD166');
  }
  if ($(this).scrollTop() >= ($('#section-4').position().top - 100)) {
    $('body').css('background-color', '#073B4C');
  }
});
body {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  background-color: #118AB2;
  transition: .3s;
}

section {
  height: 100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="section-1">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-2">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-3">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-4">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
s.kuznetsov
  • 14,870
  • 3
  • 10
  • 25
1

Here is a quick adaptation for your use case of the Observable example given on the Intersection Observer API page.

let prevRatio = 0.0;
const sectionColors = {
  'section-1': 'rgba(17, 138, 178, ratio)',
  'section-2': 'rgba(6, 214, 160, ratio)',
  'section-3': 'rgba(255, 209, 102, ratio)',
  'section-4': 'rgba(7, 59, 76, ratio)'
}

function createObserver() {
  let observer;

  let options = {
    root: root,
    rootMargin: "0px",
    threshold: buildThresholdList()
  };

  observer = new IntersectionObserver(handleIntersect, options);
  observer.observe(sectionOne);
  observer.observe(sectionTwo);
  observer.observe(sectionThree);
  observer.observe(sectionFour);
}
  
function buildThresholdList() {
  let thresholds = [];
  let numSteps = 20;

  for (let i=1.0; i<=numSteps; i++) {
    let ratio = i/numSteps;
    thresholds.push(ratio);
  }

  thresholds.push(0);
  return thresholds;
}

function handleIntersect(entries, observer) {
  entries.forEach((entry) => {
    const id = entry.target.id;
    if (entry.intersectionRatio > prevRatio) {
      entry.target.style.backgroundColor = sectionColors[id].replace("ratio", entry.intersectionRatio);
    } else {
      entry.target.style.backgroundColor = sectionColors[id].replace("ratio", entry.intersectionRatio);
    }

    prevRatio = entry.intersectionRatio;
  });
}

let root = document.getElementById('snippet-result-code');
let sectionOne = document.getElementById('section-1');
let sectionTwo = document.getElementById('section-2');
let sectionThree = document.getElementById('section-3');
let sectionFour = document.getElementById('section-4');
createObserver();
html, body, p {
  margin: 0;
  padding: 0;
}

section {
  height: 100vh;
}
<section id="section-1">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-2">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-3">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-4">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
pilchard
  • 12,414
  • 5
  • 11
  • 23