This question already has an answer here:
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/customd/jquery-visible with this function but I don't know how to make it work.
$('#element').visible( true );
You can write a jQuery function like this to determine if an element is in the viewport.
Include this somewhere after jQuery is included:
Sample usage:
Note that this only checks the top and bottom positions of elements, it doesn't check if an element is outside of the viewport horizontally.
Here's a way to do it without a plugin:
First get the position of the element. Then add the scroll position and the viewport height together.
If the combination of the scroll position and viewport height is greater than or equal to the element position, it's in the viewport.
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:You can see this example.
detectPartial :
visible
is boolean variable which indicates if the element is visible or not.Check if element is visible in viewport without plugin:
First determine the top and bottom positions of the element. Then determine the position of the viewport's bottom (relative to the top of your page) by adding the scroll position to the viewport height.
If the bottom position of the viewport is greater than the element's top position AND the top position of the viewport is less than the element's bottom position, the element is in the viewport (at least partially). In simpler terms, when any part of the element is between the top and bottom bounds of your viewport, the element is visible on your screen.
Now you can write an if/else statement, where the if statement only runs when the above condition is met.
The code below executes what was explained above:
This answer is a summary of what Chris Bier and Andy were discussing below. I hope it helps anyone else who comes across this question while doing research like I did. I also used an answer to the following question to formulate my answer: Show Div when scroll position.