How to determine if an element is visible inside the viewport

rp-7

#1

I’m currently designing the responsive version of a content-heavy b2b website and came across a challenge: How can I determine if a an element (a headline, to be precise) is currently visible in the viewport (“visible” meaning not below the fold, there’s no dynamic behavior regarding the headlines)?
I could of course use the OnScroll event and calculate the y-position, but I’m already using this for other purposes and it would get quite complicated if I had to create further ELSE IFs …

At fist I tried to use the OnShow-event, but this only relates to something being shown/hidden dynamically, and does not relate to the viewport in any way … (I guess, since I couldn’t find a proper documentation for all the events anywhere … )


#2

As far as I’m aware you’ll have to use the OnScroll event as you mentioned. But there is a trick you can do to keep from cluttering the event’s logic. Add a dynamic panel, it will remain empty and invisible. On the OnMove event of this panel, put all the logic for checking the visibility of this header (check scroll position, check window height and compare to the header’s position) that you would have put on the OnScroll event. Then, on the OnScroll event, before everything else, put a case with the action: Move (panel you jus added) by 0,0. Now when you scroll, the panel will move by 0,0, and the logic you implemented will execute.

Just make sure the case after this one isn’t set to IF ELSE so its execution won’t depend on the move you added.


#3

Hi!

The top of the viewport is always [[Window.scrollY]], and the bottom of the viewport is always [[Window.scrollY + Window.height]]. So with the following logic (assigning a local variable to your headline widget), the code after it would execute if the headline is fully visible within the viewport.

If value [[LVAR_headline.top >= Window.scrollY && LVAR_headline.bottom <= Window.scrollY + Window.height]] equals value true.

… (&& is a logical AND. Don’t forget to equate the expression to true!)

If you are scrolling a dynamic panel instead of the browser window, you’d create a local variable referencing the panel and put it in place of Window above.


#4

Hi Nathan,

Thank you for you idea!

I ended up creating something similar: From the OnScroll event (in the page interaction - panel), I set the focus onto an invisible hotspot. And then I put the logic into this hotspot (OnFocus → check condition if element A is visible → do something → else if element B is visible → do something else). For the visibility check I’ve used the area of widget-condition.

So I basically outsourced the logic from the page interaction (where I already have several conditions for other events) to another element. Problem solved :slight_smile:


closed #5

unlisted #6