jQuery Plugin For Checking If An Element Is In The Viewport - isInViewport

File Size: 73.2 KB
Views Total: 6663
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
jQuery Plugin For Checking If An Element Is In The Viewport - isInViewport

Is In Viewport is a super tiny jQuery plugin for checking if an html element is in the viewport. The plugin provides a simple method to return true if the element is in the viewport and false otherwise.

See also:

How to use it:

1. Include jQuery javascript library and jQuery Is In Viewport plugin on the web page

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="../lib/isInViewport.min.js"></script>

2. Create a group of boxes. The background-color of a box will be set to RED if it is in the viewport.

<div id="container">
<div class="box"> 1 </div>
<div class="box"> 2 </div>
<div class="box"> 3 </div>
<div class="box"> 4 </div>
<div class="box"> 5 </div>
<div class="box"> 6 </div>
<div class="box"> 7 </div>
</div>

3. The sample CSS for the boxes

.box {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
background-color: grey;
height: 501px;
width: 100%;
border-bottom: 10px solid white;
}

4. The javascript

(function($){
$(document).ready(function() {
$('#container').children().each(function() {
if ($(this).isInViewport({"tolerance" :50}))
$(this).css("background-color", "red");
else
$(this).css("background-color", "blue");
});

$(window).scroll(function() {
$('#container').children().each(function() {
if ($(this).isInViewport({"tolerance" :50,"toleranceForLast": 432, "debug": true}))
$(this).css("background-color", "red");
else
$(this).css("background-color", "blue");
});
});
});
}(jQuery));

Changelog:

v3.0.4 (2018-12-12)

  • Remove window import and rely on implicit window

v3.0.3 (2018-05-14)

  • Use the non-deprecated jQuery.expr.pseudos by default

v3.0.2 (2018-05-13)

  • Rewrite as ES6 module and update build pipeline

v2.3.1 (2017-03-13)

  • Rewrite as ES6 module and update build pipeline

v2.3.1 (2016-01-13)

  • Remove unnecessary bool coercion

v2.3.0 (2015-11-16)

  • bugs fixed

v2.2.4 (2015-04-15)

  • bugs fixed

v2.2.3 (2015-03-02)

  • bugs fixed

v2.2.1 (2015-01-12)

  • bugs fixed

v2.1.0 (2014-05-12)

  • .do() functionality added

v2.0.0 (2014-04-30)

  • fixed for mobile users
  • added some more comments and fixed some newlines

v1.1.0 (2014-03-03)

  • Added in-viewport selector

v1.0.2 (2013-10-01)

  • examples updated

This awesome jQuery plugin is developed by zeusdeux. For more Advanced Usages, please check the demo page or visit the official website.