jQuery event to trigger action when a div is made visible

后端 未结 22 2268
你的背包
你的背包 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:39

    One way to do this.
    Works only on visibility changes that are made by css class change, but can be extended to watch for attribute changes too.

    var observer = new MutationObserver(function(mutations) {
            var clone = $(mutations[0].target).clone();
            clone.removeClass();
                    for(var i = 0; i < mutations.length; i++){
                        clone.addClass(mutations[i].oldValue);
            }
            $(document.body).append(clone);
            var cloneVisibility = $(clone).is(":visible");
            $(clone).remove();
            if (cloneVisibility != $(mutations[0].target).is(":visible")){
                var visibilityChangedEvent = document.createEvent('Event');
                visibilityChangedEvent.initEvent('visibilityChanged', true, true);
                mutations[0].target.dispatchEvent(visibilityChangedEvent);
            }
    });
    
    var targets = $('.ui-collapsible-content');
    $.each(targets, function(i,target){
            target.addEventListener('visibilityChanged',VisbilityChanedEventHandler});
            target.addEventListener('DOMNodeRemovedFromDocument',VisbilityChanedEventHandler });
            observer.observe(target, { attributes: true, attributeFilter : ['class'], childList: false, attributeOldValue: true });
        });
    
    function VisbilityChanedEventHandler(e){console.log('Kaboom babe'); console.log(e.target); }
    

提交回复
热议问题