Home>

I want to create a float header with InterSection ObserverAPI.

"Failed to construct 'IntersectionObserver': The provided double value is non-finite."

Does not work with error

.
Non-finite means `` not finite '',
As long as you look at the code, I'm going to lose the finite part ...

Here are the HTML and JS code.

<! DOCTYPE html>
<html>
  <head>
    <title>float header</title>
    <meta charset = "UTF-8" />
  </head>
  <body>
    
      
        header
      
      
        Sample 1
      
      
        Sample 2
      
      
        Sample 3
      
      
        Sample 4
      
    
    <script src = "src/index.js"></script>
  </body>
</html>
import "./styles.css";
const $header = document.querySelector (". header");
// Get header DOM
const options = {
  root: null,
  rootMargin: 0,
  threshold: "300px"
  // threshold is the setting value of how much the callback function is called
  // watchHeader is executed at 300px intersection
};

const observer = new IntersectionObserver (watchHeader, options);
// Define a function to do when crossing the first argument
observer.observe ($header);
// Observe header with observer
function watchHeader (entry) {
  if (entry.isIntersecting) {
    entry.target.classList.add ("is-float");
    // Give position: fixed;with is-float
  }
}
Code

Thanks for your patience.

  • Answer # 1

    I read Intersection Observer API.

    Options given to the second argument are

    root: Element used as viewport

    margin: Character string used as css margin notation

    threshold: Specify when to fire the callback
    If the value is between 0 and 1, it fires once, and in the case of an array with a decimal value between 0 and 1 as an array element, fires at each timing

    Shouldn't it be in the form of

    ?

Related articles