A utility library for observing visibility changes of DOM elements. Immediately know when an element becomes hidden, partly visible or fully visible.
VisSense.js is lightweight (<4KB minified and gzipped), tested and documented. Best of all: No dependencies.
- provides methods for detecting visibility of DOM elements
- provides a convenience class with straightforward methods like
isHidden,isVisible,isFullyVisible,percentage - provides a convenience class for detecting changes in visibility
- detect if an element is overlapped by others
- take elements opacity into account
- take scrollbars into account - elements "hidden" behind scrollbars are considered visible
Check out this bin for a quick demo, or here. See more examples on the demo page.
In this simple example a video will only be started if at least 75% of its area is in the users viewport:
var video = $('#video');
var videoVisibility = VisSense(video[0]);
if(videoVisibility.percentage() > 0.75) {
video.play();
}In the following example the video will be started if it's at least 75% visible and stopped as soon as it is not visible anymore:
var video = $('#video');
var visibility = VisSense(video[0], { fullyvisible: 0.75 });
var visibility_monitor = visibility.monitor({
fullyvisible: function() {
video.play();
},
hidden: function() {
video.stop();
}
}).start();See a slightly adapted version of this example live and try it on jsbin.com.
See vissense.github.io/vissense or generate the documentation locally.
Clone the repository and run grunt docs
Install with npm
npm install vissense --save
Install with bower
bower install vissense/vissense --save
- Issue Tracker: https://github.com/vissense/vissense/issues
- Source Code: https://github.com/vissense/vissense
git clone https://github.com/vissense/vissense.git
npm install -g grunt-cli
npm install -g karma-cli
npm install -g bower
npm install
bower install
grunt
grunt test
or
grunt serve
and it automatically opens http://localhost:3000/SpecRunner.html in your browser.
Object constructor. Options:
hidden(default: 0) - if percentage is equal or below this limit the element is considered hiddenfullyvisible(default: 1) - if percentage is equal or above this limit the element is considered fully visible
Note: you can omit new keyword when calling VisSense(...)
gets the current visible percentage (0..1)
.isHidden()
true if element is hidden
true if element is visible
true if element is fully visible
returns an object representing the current state
{
"code": 0,
"state": "hidden",
"percentage": 0,
"visible": false,
"fullyvisible": false,
"hidden": true,
"previous": {}
}This is an alias for getting a VisSense.VisMon object observing the current element. See the options below for more details.
var element = document.getElementById('video');
var visibility_monitor = VisSense(element).monitor({
visible: function() {
console.log('visible');
},
hidden: function() {
console.log('hidden');
}
}).start();A monitor object lets you observe an element over a period of time. It emits certain events you can subscribe to, and it can be extended with custom logic.
Object constructor. Options:
strategya strategy (or array of strategies) for observing the element. VisSense comes with two predefined strategies. See below.startfunction to run when monitoring the element startsstopfunction to run when monitoring the element stopsupdatefunction to run when elements update function is calledhiddenfunction to run when element becomes hiddenvisiblefunction to run when element becomes visiblefullyvisiblefunction to run when element becomes fully visiblevisibilitychangefunction to run when the visibility of the element changespercentagechangefunction to run when the percentage of the element changesasynca boolean flag indicating whether events are synchronous or asynchronous
var visobj = VisSense(document.getElementById('video'));
var visibilityMonitor = VisSense.VisMon(visobj, {
strategy: [
new VisSense.VisMon.Strategy.EventStrategy({ throttle: 42 })
],
visibilitychange: function() {
console.log('visibilitychange');
},
visible: function() {
console.log('element became visible');
}
}).start();Strategies are hooks which let you intercept the monitoring process. e.g. updating the monitor, sending custom events, etc.
VisSense comes with two predefined strategies:
PollingStrategya simple strategy which invokesupdate()periodically.EventStrategythis strategy registers event handlers forvisibilitychange,scrollandresizeevents and callsupdate()accordingly.
A monitor can use any number of strategies. The default monitor uses a combination of EventStrategy and PollingStrategy. Feel free to write your own strategy to cover your specific requirements (it's super easy).
You can also pass an empty array if you don't want to use any strategy.
starts observing the element returns this
stops observing the element
manually run the update procedure. this will fire all registered hooks accordingly e.g. when a percentage change happened.
returns a state object
{
"code": 1,
"state": "visible",
"percentage": 0.55,
"visible": true,
"fullyvisible": false,
"hidden": false
"previous" : {
"code": 2,
"state": "fullyvisible",
"percentage": 1,
"visible": true,
"fullyvisible": true,
"hidden": false
}
} registers an event hook
visibility_monitor.on('percentagechange', function() { ... });There is a builder available if you want to build more complex monitor objects.
var visobj = VisSense(document.getElementById('video'));
var visibilityMonitor = VisSense.VisMon.Builder(visobj)
.strategy(new VisSense.VisMon.Strategy.ConfigurablePollingStrategy({
hidden: 1000,
visible: 2000,
fullyvisible: 5000
}))
.strategy(new VisSense.VisMon.Strategy.EventStrategy({ throttle: 200 }))
.strategy(new VisSense.VisMon.Strategy.UserActivityStrategy({ inactiveAfter: 60000 }))
.strategy(new VisSense.VisMon.Strategy.PercentageTimeTestEventStrategy('50%/10s', {
percentageLimit: 0.5,
timeLimit: 10000,
interval: 100
}))
.strategy({
start: function(monitor) {
setTimeout(function() {
monitor.publish('mySpecialEvent');
}, 10000);
}
})
.on('start', function (monitor) {
console.log('[Visibility Monitor] Started!');
})
.on('stop', function (monitor) {
console.log('[Visibility Monitor] Stopped!');
})
.on('visible', function (monitor) {
console.log('[Visibility Monitor] Element became visible!');
})
.on('50%/10s', function (monitor) {
console.log('[Visibility Monitor] Element was >50% visible for 10 seconds!');
})
.on('mySpecialEvent', function (monitor) {
console.log('[Visibility Monitor] MySpecialEvent received!');
})
.build()
.startAsync();This example uses external strategies. See UserActivityStrategy, PercentageTimeTestEventStrategy and ConfigurablePollingStrategy for more information.
The project is licensed under the MIT license. See LICENSE for details.

