Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observing Display Changes in jQuery

Tags:

jquery

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!

like image 411
Kevin Sylvestre Avatar asked Jun 16 '11 16:06

Kevin Sylvestre


2 Answers

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

like image 175
Mark Coleman Avatar answered Sep 20 '22 20:09

Mark Coleman


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().

like image 45
Lepidosteus Avatar answered Sep 20 '22 20:09

Lepidosteus