Detecting an Element is in a specific position on the screen

Detecting an Element Is in the Screen.

Scenario

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 Out of the screen       in the screen (particially)   in the screen (strictly)

+----------------+
|element |
| |
+----------------+ +--------------+
| element |
+------------------+ +--------------------+ +--------------------+
| | | +--------------+ | | |
| | | | | +--------------+ |
| | | | | | element | |
| screen | | screen | | | | |
| | | | | +--------------+ |
| | | | | screen |
| | | | | |
+------------------+ +--------------------+ +--------------------+

+----------------+
|element |
| |
+----------------+

Window and Element Model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
scrollY:

-n


0 +----------------------+ <-------------+ windowTop
| |
| |
+-------------------------------+ <---------+ elementTop
| | | |
| | | |
| | | |
+-------------------------------+ <---------+ elementBottom
| |
| |
+----------------------+ <-------------+ windowBottom
n

Vanilla Javascript

1
2
3
4
5
6
7
8
9
10
11

var windowTop = window.scrollY;
var windowBottom = windowTop + window.innerHeight;
var elementTop = Math.ceil(element.getBoundingClientRect().top + document.body.scrollTop);
var elementBottom = elementTop + Math.ceil(element.getBoundingClientRect().height);

if ((windowTop < elementTop) && (windowBottom > elementBottom)) {
// in the screen (strict)
} else if ((elementTop <= windowBottom) && (elementBottom >= windowTop)) {
// int the screen (particial)
}

jQuery

1
2
3
4
5
6
7
8
9
10
11

var windowTop = $(window).scrollTop();
var windowBottom = windowTop + $(window).height();
var elementTop = Math.ceil($(element).offset().top);
var elementBottom = elementTop + $(element).height();

if ((windowTop < elementTop) && (windowBottom > elementBottom)) {
// in the screen (strict)
} else if ((elementTop <= windowBottom) && (elementBottom >= windowTop)) {
// int the screen (particial)
}