Is it possible to add an observer to a DOM element that is triggered on changes to the visibility (i.e. calls to show()
and hide()
)? Thanks!
If you want to observe any call to .show()
or .hide()
and have access to jQuery 1.5+ you could use jQuery.sub()
to create a copy of the jQuery object to override the default .show()
or .hide()
actions.
var myjQuery = jQuery.sub();
myjQuery.fn.hide = function() {
alert('hide');
return jQuery.fn.hide.apply(this, arguments);
};
myjQuery.fn.show = function() {
alert('show');
return jQuery.fn.show.apply(this, arguments);
};
And then using the .sub()
copy
(function($) {
$(document).ready(function() {
$(".click").click(function() {
if ($("#hide").is(":visible")) {
$("#hide").hide();
}
else {
$("#hide").show();
}
});
});
})(myjQuery);
Example on jsfiddle
It is not possible out of the box that I know of, but if changes happens through jquery you can easily add the tracking yourself by using a custom event like this:
// save the jquery.show() method
$.prototype.base_show = $.prototype.show;
// provide your own that trigger the event then call the original one
$.prototype.show = function(speed, easing, callback) {
// call your custom event, add any parameters you need there
$(window).trigger('on_jquery_show'/*, params you need*/);
// now call the "real" show method
$.prototype.base_show(speed, easing, callback);
// return this so you can chain it
return this;
};
// add some callback to that custom event
$(window).bind('on_jquery_show', function() { console.log('show !'); });
// it works !
$('#some_div').show().show();
Same thing for hide().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With