user962642
user962642

Reputation: 299

How can I scroll to first visible element with a specific div class?

Is there anyway to automatically scroll to the first visible element with a certain div class using javascript?

thanks!

Upvotes: 14

Views: 21899

Answers (2)

tsi
tsi

Reputation: 1264

Can be easily done with plain JS:

const items = container.getElementsByClassName('active');
const visible = [...items].filter((el) => {
  // jQuery-like :visible selector
  return !!( el.offsetWidth || el.offsetHeight || el.getClientRects().length );
});

if (visible.length > 0) {
  container.scrollTo({
    top: items[0].offsetTop,
    behavior: 'smooth'
  });
}

This assumes:

  • container is your scrollable container, you can replace with document & window if you're trying to scroll the whole page.
  • You're looking for the first item with an active class name.
  • You'd like a smooth scroll, remove the behavior: 'smooth' config if you want the scroll to happen instantly in a single jump.

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo

Upvotes: 2

Blender
Blender

Reputation: 298246

You should be able to use something like this:

$('html, body').animate({
    scrollTop: $('.class:visible:first').offset().top
}, 1000);

Demo: http://jsfiddle.net/Blender/xUw54/2/

Upvotes: 39

Related Questions