Return to Solutions Overview <-

How to check if an element is visible in the viewport using jQuery (JavaScript)

(Still under development as of March 15th 2023)

Here's a cool snippet I found in stack overflow.
Super useful if you're building custom interactions!

// Is element in viewport
‍
$.fn.isInViewport = function() {
   var elementTop = $(this).offset().top
   var elementBottom = elementTop + $(this).outerHeight()

   var viewportTop = $(window).scrollTop()
   var viewportBottom = viewportTop + $(window).height()

   return elementBottom > viewportTop && elementTop < viewportBottom
}

Here is the documentation that explains what $.fn is.



You can use the code in something like that -->

// *** Progress bar code ***
‍
// Define global elements
const array_of_$_triggers = $('.progress-bar_circle.hide-tablet')
const $_left_arrow = $('.stack2_arrow-cnt').find('.js-prev')
const $_right_arrow = $('.stack2_arrow-cnt').find('.js-next')

// Define global strings    
const s_slides = '.stack2-slide'

‍
// Main function
function main() {

   $(s_slides).each(function(i) {
       // Define element
       var $_slide = $(this)

       if ( $_slide.isInViewport() ) {
           console.log(i)
       }
   })
   
}


// Helper functions

// Is element in viewport
$.fn.isInViewport = function() {
   var elementTop = $(this).offset().top
   var elementBottom = elementTop + $(this).outerHeight()

   var viewportTop = $(window).scrollTop();
   var viewportBottom = viewportTop + $(window).height()

   return elementBottom > viewportTop && elementTop < viewportBottom
}


// Call main function
main()

FAQs

You still have an open question about BMG.studio and how we operate. Chances are good that you will find what you are looking for here:

Why does this FAQ exist?

Well. As of Wednesday, March 15th 2023, I think this component looks really cool.

Can I clone this FAQ component?

Yes. Yes you can. You can do so -> here <-

Still have questions?

It's okay to reach out. Use either email or our calendar tool