Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How hard would it be to support absolutely positioned elements? #128

Open
ndbroadbent opened this issue Sep 9, 2017 · 3 comments
Open

Comments

@ndbroadbent
Copy link

The native webkit scrollIntoViewIfNeeded supports this, and I need this for my app. If it's too hard to implement here, are there any alternatives?

@ndbroadbent
Copy link
Author

dom-scroll-into-view handles absolute positions correctly, so I switched to that library

@stipsan
Copy link
Member

stipsan commented Oct 1, 2017

Glad you found a package that works for you 👍

I'm reopening this though as I think this is something this package should support as well 🙂

@stipsan stipsan reopened this Oct 1, 2017
@aroc
Copy link

aroc commented Nov 22, 2023

This library doesn't handle it well, but you can do your own check reasonably easy here before calling the function. Ex:

function findScrollableParent(element: HTMLElement) {
  while (element) {
    if (element === document.body) {
      // Reached the body element, no scrollable parent found
      return null;
    }

    const overflowY = window.getComputedStyle(element).overflowY;
    const isScrollable = overflowY === "auto" || overflowY === "scroll";
    const canScroll =
      isScrollable && element.scrollHeight > element.clientHeight;

    if (canScroll) {
      return element;
    }

    element = element.parentElement as HTMLElement;
  }
  return null;
}

function isElementVisible(elementSelector: string) {
  const element = document.querySelector(elementSelector);
  if (!element) {
    return false; // Not found
  }
  const scrollableParent = findScrollableParent(element as HTMLElement);

  if (!scrollableParent) {
    return false; // No scrollable parent found
  }

  const elRect = element.getBoundingClientRect();
  const parentRect = scrollableParent.getBoundingClientRect();

  // Check if the element is within the visible area of the parent
  const isVisible =
    elRect.top >= parentRect.top &&
    elRect.left >= parentRect.left &&
    elRect.bottom <= parentRect.bottom &&
    elRect.right <= parentRect.right;

  return isVisible;
}

// Usage
const el = document.getElementById(id);

  // Usage example
  const isVisible = isElementVisible(`#${id}`);
  if (!isVisible) {
    scrollIntoView(el, {
      behavior: "smooth",
      block: "center",
      inline: "center",
      scrollMode: "if-needed",
    });
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants