


VisSense.js
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.
What it does
provides methods for detecting visibility of DOM elements provides a convenience class with straightforward methods likeisHidden
, isVisible
, isFullyVisible
, percentage
provides a convenience class for detecting changes in visibilityWhat it does not do (by default)
detect if an element is overlapped by others take elements opacity into account take scrollbars into account - elements "hidden" behind scrollbars are considered visibleDemos and Examples
Check out this bin for a quick demo. 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.Documentation
See vissense.github.io/vissense or generate the documentation locally.Generate documentation
Clone the repository and rungrunt docs
Download
npm
Install with npmnpm install vissense --save
Bower
Install with bowerbower install vissense/vissense --save
Github
Download from Githubcdnjs
Reference from cdnjs.comContribute
- Issue Tracker: https://github.com/vissense/vissense/issues
- Source Code: https://github.com/vissense/vissense
Clone Repository
git clone https://github.com/vissense/vissense.git
Install dependencies
npm install -g grunt-cli
npm install -g karma-cli
npm install -g bower
npm install
bower install
Build project
grunt
Run tests
grunt test
or
grunt serve
and it automatically opens
http://localhost:3000/SpecRunner.html
in your browser.API
VisSense(element , options)
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(...)
.percentage()
gets the current visible percentage (0..1).isHidden()
true
if element is hidden.isVisible()
true
if element is visible.isFullyVisible()
true
if element is fully visible.state()
returns an object representing the current state{
"code": 0,
"state": "hidden",
"percentage": 0,
"visible": false,
"fullyvisible": false,
"hidden": true,
"previous": {}
}
.monitor(config)
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();
VisSense.VisMon(visobj , options)
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:
strategy
a strategy (or array of strategies) for observing the element. VisSense comes with two predefined strategies. See below.start
function to run when monitoring the element startsstop
function to run when monitoring the element stopsupdate
function to run when elements update function is calledhidden
function to run when element becomes hiddenvisible
function to run when element becomes visiblefullyvisible
function to run when element becomes fully visiblevisibilitychange
function to run when the visibility of the element changespercentagechange
function to run when the percentage of the element changesasync
a 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
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: -
PollingStrategy
a simple strategy which invokes update()
periodically.
- EventStrategy
this strategy registers event handlers for visibilitychange
, scroll
and resize
events and calls update()
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..start()
starts observing the element returnsthis
.stop()
stops observing the element.update()
manually run the update procedure. this will fire all registered hooks accordingly e.g. when a percentage change happened..state()
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
}
}
.on(event, hook)
registers an event hookvisibility_monitor.on('percentagechange', function() { ... });
Builder
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.