jQuery when element becomes visible
css, html, javascript, jquery
Solution
There are no events in JQuery to detect css changes. Refer here: onHide() type event in jQuery It is possible:
DOM L2 Events module defines mutation events; one of them - DOMAttrModified is the one you need. Granted, these are not widely implemented, but are supported in at least Gecko and Opera browsers. Source: Event detect when css property changed using Jquery
Without events, you can use `setInterval` function, like this:
var maxTime = 5000, // 5 seconds
startTime = Date.now();
var interval = setInterval(function () {
if ($('#element').is(':visible')) {
// visible, do something
clearInterval(interval);
} else {
// still hidden
if (Date.now() - startTime > maxTime) {
// hidden even after 'maxTime'. stop checking.
clearInterval(interval);
}
}
},
100 // 0.1 second (wait time between checks)
);
Note that using `setInterval` this way, for keeping a watch, may affect your page's performance.
7th July 2018: Since this answer is getting some visibility and up-votes recently, here is additional update on detecting css changes:
Mutation Events have been now replaced by the more performance friendly Mutation Observer.
The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature which was part of the DOM3 Events specification.
Refer: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
Problem
Basically, I am wondering if there is a way to automatically run a function when an element becomes hidden or visible, not on a user click but automatically in another script. I don't want this to just run one time, because the elements (such as a slider) constantly change from visible to hidden. Would this be something that jQuery can do with bind? Such as binding the element's visibility to a function (I don't know how to write this) If you need me to elaborate more on what I'm trying to do, let me know. Thanks Pseudocode: ``` $('#element').bind('display:none', function); function(){ //do something when element is display:none } $('#element').bind('display:block', function2); function2(){ //do opposite of function } ```