Vim Bonsu Vim Bonsu - 17 days ago 10
Javascript Question

Jquery check if element is visible in viewport

Function to check if the div class "media" is within the browsers visual viewport regardless of the window scroll position.

<HTML>
<HEAD>
<TITLE>My first HTML document</TITLE>
</HEAD>
<BODY>
<div class="main">
<div class="media"></div>
</div>

</BODY>
</HTML>


Trying to use this plugin https://github.com/teamdf/jquery-visible/ with this function but
I don't know how to make it work.

$('#element').visible( true );

Answer

Well, how did you try to make it work? According to the documentation for that plugin, .visible() returns a boolean indicating if the element is visible. So you'd use it like this:

if ($('#element').visible(true)) {
    // The element is visible, do something
} else {
    // The element is NOT visible, do something else
}

Another jQuery plugin I've used is this one which adds viewport selectors. So instead of checking a boolean value, you'd select elements based on their visibility:

$('#element:in-viewport').doSomething();
Comments