How to detect when a element in page changes visibility?
Please read good the question.
The reference it’s not only to :visible
pseudo selector, but also on visibility
visible/hidden.
After some search you could find that there’s a plugin that does this job.
Snippet here:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
"use strict";
((typeof jQuery === "function") && !((function($,w){
$.fn.extend({
detectVisibilityChange : function(callback) {
this.checkForVisiblilityChange(callback);
return this;
},
checkForVisiblilityChange : function(callback) {
if(!(this.length >>>0 ))
return undefined;
var elem,i=0;
while ( ( elem = this[ i++ ] ) ) {
var curValue = $(elem).is(":visible");
(elem.lastVisibility === undefined) && (elem.lastVisibility = curValue);
(curValue !== elem.lastVisibility) && (
elem.lastVisibility = curValue,
(typeof callback === "function") && (
callback.apply(this, [new jQuery.Event('visibilityChanged'), curValue ? "shown" : "hidden"])
),
(function(elem, curValue, w){
w.setTimeout(function(){
$(elem).trigger('visibilityChanged',[curValue ? "shown" : "hidden"])
},10)
})(elem, curValue, w)
)
}
(function(that, a, w){
w.setTimeout(function(){
that.checkForVisiblilityChange.apply(that,a);
},10)
})(this, arguments, w)
}
})
})(jQuery, window))) || console.error("detectVisibilityChange plugin requires jQuery")
</script>
<center>
<button id="toggle_visiblity" type="button" style="display: block;"> Hide / Show div</button>
<div id="test_hidden" style="display: none;">EVENT (also when close this)</div>
</center>
<script>
$("#toggle_visiblity").click(function(){
var visible = $("#test_hidden").is(":visible")
$("#test_hidden")[visible ? "hide" : "show"]();
})
$("#test_hidden").detectVisibilityChange(function(e, visibility){
console.log("Visibility changes: " + visibility , e)
})
</script>
but it works only for :visible
pseudo selector (not for visibility
visible/hidden) and if you try to expand the selection from a single element $("#test_hidden")
to a class $(".class")
or each element in page $("*")
it does not work well.
So, in the end, how to detect when a page element changes visibility?
There’s a way to modify this, or there’s also an other way to have the required result?