1

I have a section with a class name 'concert-landing-synopsis' and on a scroll, I want to check if the section is on focus and add a class name to a different element. I have looked through some of the solutions here the focused variable is always false

let activateElement = document.getElementsByClassName("concert-landing-synopsis");

if (activateElement.length > 0) {
  window.onscroll = _ => {
    let isFocused = (document.activeElement === activateElement[0]);

    if (isFocused) {
      console.log("On focus");
    }
  };
}

The view is something like this

<section class="concert-landing-details">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</section>
MTCoster
  • 5,307
  • 3
  • 25
  • 46
aj12
  • 238
  • 3
  • 15
  • 1
    The section element isn't focusable. You can see here https://stackoverflow.com/questions/1599660/which-html-elements-can-receive-focus what elements are actually focusable. – shyyko.serhiy Dec 19 '18 at 22:07
  • 1
    What I imagine you are trying to achieve is to check if the element is visible in scrollable container. You should see https://stackoverflow.com/questions/487073/how-to-check-if-element-is-visible-after-scrolling . – shyyko.serhiy Dec 19 '18 at 22:09

1 Answers1

0

You need to loop through all the elements returned by document.getElementsByClassName('concert-landing-synopsis'), as in

document.getElementsByClassName('concert-landing-synopsis').forEach((el) => {
   const isFocused = (document.activeElement === el);
});