Reputation: 38052
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!
Upvotes: 11
Views: 4341
Reputation: 23943
Assuming you're showing and hiding using the jQuery mechanisms, you might try using the Live Query plugin.
Live Query also has the ability to fire a function (callback) when it matches a new element and another function (callback) for when an element is no longer matched.
Upvotes: 0
Reputation: 40863
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);
Upvotes: 8
Reputation: 146310
Yes you can:
For example:
$('#divID').show('slow', function() {
// Animation complete.
});
See the docs
Upvotes: 0
Reputation: 12047
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().
Upvotes: 1