jQuery event to trigger action when a div is made visible

后端 未结 22 2611
你的背包
你的背包 2020-11-22 12:03

I\'m using jQuery in my site and I would like to trigger certain actions when a certain div is made visible.

Is it possible to attach some sort of \"isvisible\" even

22条回答
  •  攒了一身酷
    2020-11-22 12:36

    I changed the hide/show event trigger from Catalint based on Glenns idea. My problem was that I have a modular application. I change between modules showing and hiding divs parents. Then when I hide a module and show another one, with his method I have a visible delay when I change between modules. I only need sometimes to liten this event, and in some special childs. So I decided to notify only the childs with the class "displayObserver"

    $.each(["show", "hide", "toggleClass", "addClass", "removeClass"], function () {
        var _oldFn = $.fn[this];
        $.fn[this] = function () {
            var hidden = this.find(".displayObserver:hidden").add(this.filter(":hidden"));
            var visible = this.find(".displayObserver:visible").add(this.filter(":visible"));
            var result = _oldFn.apply(this, arguments);
            hidden.filter(":visible").each(function () {
                $(this).triggerHandler("show");
            }); 
            visible.filter(":hidden").each(function () {
                $(this).triggerHandler("hide");
            });
            return result;
        }
    });
    

    Then when a child wants to listen for "show" or "hide" event I have to add him the class "displayObserver", and when It does not want to continue listen it, I remove him the class

    bindDisplayEvent: function () {
       $("#child1").addClass("displayObserver");
       $("#child1").off("show", this.onParentShow);
       $("#child1").on("show", this.onParentShow);
    },
    
    bindDisplayEvent: function () {
       $("#child1").removeClass("displayObserver");
       $("#child1").off("show", this.onParentShow);
    },
    

    I wish help

提交回复
热议问题