ThuZ
ThuZ

Reputation: 1

How can I make text popup when I scroll to it?

I want the textblocks on my website to get bigger/popup when I scroll down to them. How can I do that?

I tried to google how to do that but I couldn´t figure that out.

Upvotes: 0

Views: 133

Answers (2)

PeteZionDev
PeteZionDev

Reputation: 19

This example will make the font size of the text blocks increase to 24px as they are scrolled into view.

window.addEventListener('scroll', function() {
  var textBlock1 = document.getElementById('text-block-1');
  var textBlock2 = document.getElementById('text-block-2');

  // Get the position of the text blocks relative to the viewport
  var rect1 = textBlock1.getBoundingClientRect();
  var rect2 = textBlock2.getBoundingClientRect();

  // Check if the text blocks are within the viewport
  if (rect1.top < window.innerHeight && rect1.bottom > 0) {
    textBlock1.style.fontSize = '24px';
  }
  if (rect2.top < window.innerHeight && rect2.bottom > 0) {
    textBlock2.style.fontSize = '24px';
  }
});

Upvotes: -1

Ciprian
Ciprian

Reputation: 882

You need to use the IntersectionObserver API to detect when the text block is visible, then apply a CSS class.

Try this:

const element = document.querySelector('.text-block-1');

const observer = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
        element.classList.add('visible');
    }
});

observer.observe(element);

And then use the visible class, like this:

.visible { color: red; font-size: 24px; }

Note that if you have multiple HTML elements using the same class, you will need to use document.querySelectorAll and create a loop to observe all elements.

Upvotes: 2

Related Questions