Skip to content

Instantly share code, notes, and snippets.

@Raynos Raynos/visibility.js
Created Dec 21, 2012

Embed
What would you like to do?
var EventEmitter = require("events").EventEmitter
function visibility() {
var visHash = {
hidden: "visibilitychange"
, mozHidden: "mozvisibilitychange"
, webkitHidden: "webkitvisibilitychange"
, msHidden: "msvisibilitychange"
, oHidden: "ovisibilitychange" /* not currently supported */
}
, change
, hidden
, events = new EventEmitter()
Object.keys(visHash).some(function (key) {
var prop = visHash[key]
if (key in document) {
change = prop
hidden = key
return true
}
})
if (change) {
document.addEventListener(change, handleChange)
} else if (document.onfocusin !== undefined) {
document.attachEvent("onfocusin", handleChange)
document.attachEvent("onfocusout", handleChange)
} else {
window.addEventListener("focus", handleChange)
window.addEventListener("blur", handleChange)
}
return events
function handleChange(event) {
var visible
event = event || window.event
if (event.type === "focus" || event.type === "focusin") {
visible = true
} else if (event.type === "blur" || event.type === "focusout") {
visible = false
} else {
visible = document[hidden]
}
if (visible) {
events.inFocus = true
events.emit("focus")
} else {
events.inFocus = false
events.emit("blur")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.