Skip to content

Commit 311c64a

Browse files
author
frontid
authored
Add plugin
1 parent 12693c6 commit 311c64a

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

isInViewport.jquery.js

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/* ====================================================
2+
* jQuery Is In Viewport.
3+
* https://github.com/frontid/jQueryIsInViewport
4+
* Marcelo Iván Tosco (capynet)
5+
* Inspired on https://stackoverflow.com/a/40658647/1413049
6+
* ==================================================== */
7+
!function ($) {
8+
'use strict'
9+
10+
var plugin
11+
12+
var Class = function (el, cb) {
13+
plugin = this
14+
this.$el = $(el)
15+
this.cb = cb
16+
watch()
17+
return this
18+
}
19+
20+
/**
21+
* Checks if the element is in.
22+
*
23+
* @returns {boolean}
24+
*/
25+
function isIn () {
26+
var $win = $(window)
27+
var elementTop = plugin.$el.offset().top
28+
var elementBottom = elementTop + plugin.$el.outerHeight()
29+
var viewportTop = $win.scrollTop()
30+
var viewportBottom = viewportTop + $win.height()
31+
return elementBottom > viewportTop && elementTop < viewportBottom
32+
}
33+
34+
/**
35+
* Launch a callback indicating when the element is in and when is out.
36+
*/
37+
function watch () {
38+
var _isIn = false
39+
40+
$(window).on('resize scroll', function () {
41+
42+
if (isIn() && _isIn === false) {
43+
plugin.cb('entered')
44+
_isIn = true
45+
}
46+
47+
if (_isIn === true && !isIn()) {
48+
plugin.cb('leaved')
49+
_isIn = false
50+
}
51+
52+
})
53+
}
54+
55+
// jQuery plugin.
56+
//-----------------------------------------------------------
57+
$.fn.isInViewport = function (cb) {
58+
return this.each(function () {
59+
var $element = $(this)
60+
var data = $element.data('isInViewport')
61+
if (!data) {
62+
$element.data('isInViewport', (new Class(this, cb)))
63+
}
64+
})
65+
}
66+
67+
}(window.jQuery)

0 commit comments

Comments
 (0)