Although the original poster has asked for a JQuery solution, they have also added a JavaScript tag on the question which permits adding this more modern solution as well:
TLDR:
Use the IntersectionObserver API.
Here are two sandboxes I've made both in vanilla JavaScript and in React to show this in working examples:
- Vanilla JavaScript example sandbox
- React example sandbox (uses the react-intersection-observer NPM module)
A bit longer answer: It's been more than 10 years since this question was asked and at that time using these JQuery solutions made sense, but today we don't need JQuery for such need anymore:
The Intersection Observer API provides a way to observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.
It's very easy to use, first create an observer and pass it what you want to do when it's triggered (a callback function), and also optionally pass an options object too, e.g., in the case of this question, we'll need the threshold option with value of 1 to make sure the element is completely within the viewport, and if not, then we'll know that it's "offscreen":
const doable = () => {
//do something
}
const observer = new IntersectionObserver(doable, { threshold: 1 });
Now call the observe()
method of it and pass the element you want to observe to it:
observer.observe(observee)