I want to know if an element is currently visible in the viewport , i.e. in the browser viewport, using JavaScript/jQuery.
From this other question , I know that with .is(':visible')
I can find out if that element is visible or not, but that does not mean that it is inside the display window (and therefore invisible to the user), which is what I want.
For example: The following code checks if an element is visible when the button is clicked; but if we scroll, go down to the bottom of the page and press the button again, it keeps telling us that it is, even though the user can no longer see it.
$("button").on("click", function() {
alert($("#holamundo").is(":visible"));
});
button {
position:fixed;
top:5px;
right:5px;
}
p {
margin-top: 800px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>¿Está "Hola Mundo" visible?</button>
<div id="holamundo">Hola Mundo</div>
<p>.</p>
<p>.</p>
Is there any proper function or how would it be done in JavaScript/jQuery to detect if an element is visible AND in the viewport?