Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  58] [ 3]  / answers: 1 / hits: 129365  / 11 Years ago, tue, december 10, 2013, 12:00:00

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
}

More From » jquery

 Answers
13

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


[#73827] Sunday, December 8, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sidneyh

Total Points: 118
Total Questions: 108
Total Answers: 105

Location: Mali
Member since Fri, Jun 18, 2021
3 Years ago
sidneyh questions
Tue, Jun 7, 22, 00:00, 2 Years ago
Wed, Apr 13, 22, 00:00, 2 Years ago
Wed, Aug 12, 20, 00:00, 4 Years ago
Wed, Jun 3, 20, 00:00, 4 Years ago
Fri, Apr 24, 20, 00:00, 4 Years ago
;