Intersection observer API - "observer" parameter in callback function example

Hello,

In the page about the intersection observer API, there is an example of callback function taking a second parameter observer (under the “Handling intersection changes” section):

function handleIntersect(entries, observer) {
  entries.forEach((entry) => {
    if (entry.intersectionRatio > prevRatio) {
      entry.target.style.backgroundColor = increasingColor.replace("ratio", entry.intersectionRatio);
    } else {
      entry.target.style.backgroundColor = decreasingColor.replace("ratio", entry.intersectionRatio);
    }
    prevRatio = entry.intersectionRatio;
  });
}

My question is: what is the purpose of that observer parameter in this example? What does it do?

Hello @aganor

i did not dive in the intersection observer api but i guess the observer here is the observer object that observe it and get triggered
like when you use event in the event handler function sometime you need to get the event.target to know which trigger that event
so in observer maybe you have some common between some observer so you have one method handle them and depend on the observer you just check which one and do the modifications

so to make sure that is the case try to create 2 observer and use the console.log to monitor if that the case or not
hope that help and have a nice day :slight_smile:

1 Like

Hello @aganor

i just started a local server and test it using the following code

<head>
<style>
#box {
  background-color: rgba(40, 40, 190, 255);
  border: 4px solid rgb(20, 20, 120);
  transition: background-color 1s, border 1s;
  width: 350px;
  height: 350px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.vertical {
  color: white;
  font: 32px "Arial";
}

.extra {
  width: 350px;
  height: 350px;
  margin-top: 10px;
  border: 4px solid rgb(20, 20, 120);
  text-align: center;
  padding: 20px;
}
#x{
height: 600px;
}

</style>
</head>
<body>
<div id="x">
</div>
<div id="box">
  <div class="vertical">
    Welcome to <strong>The Box!</strong>
  </div>
</div>
<script>
const numSteps = 20.0;

let boxElement;
let prevRatio = 0.0;
let increasingColor = "rgba(40, 40, 190, ratio)";
let decreasingColor = "rgba(190, 40, 40, ratio)";

// Set things up
window.addEventListener("load", (event) => {
  boxElement = document.querySelector("#box");

  createObserver();
}, false);
function createObserver() {
  let observer;

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

  observer = new IntersectionObserver(handleIntersect, options);
  observer.observe(boxElement);
}
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, obs) {
console.log(obs);
  entries.forEach((entry) => {
    if (entry.intersectionRatio > prevRatio) {
      entry.target.style.backgroundColor = increasingColor.replace("ratio", entry.intersectionRatio);
    } else {
      entry.target.style.backgroundColor = decreasingColor.replace("ratio", entry.intersectionRatio);
    }

    prevRatio = entry.intersectionRatio;
  });
}

</script>
</body>
</html>

same as example i just change this line
function handleIntersect(entries, obs) { to make sure that i did not missed something and observer is not get caught here
and also add
console.log(obs); and if you check the console in the browser you would see it print the observer data so i am more convensed that it’s the observer that trigger it same as when we use the event handling

hope that help and have a nice day :slight_smile:

1 Like

I haven’t worked with the intersection observer API myself, yet. I think @justsomeone is right, that this parameter is like the event object in event handlers. It’s a reference to the observer itself which can be used in the callback function. Like the event object this parameter is optional as we see in the above example where only “entries” is used.
From MDN | IntersectionObserver():

callback

A function which is called when the percentage of the target element is visible crosses a threshold. The callback receives as input two parameters:

entries

An array of IntersectionObserverEntry objects, each representing one threshold which was crossed, either becoming more or less visible than the percentage specified by that threshold.

observer

The IntersectionObserver for which the callback is being invoked.

Cheers,
Michael

1 Like

Hello,

Thank you very much for the explanations and example. It’s much clearer for me now. I was a bit confused to see many IO examples online with callback functions taking that parameter (probably due to copy pasting) without being used later.

1 Like

you very welcome and glad to help MDN has great documentation that why many get bite from it :wink: