Event listener for when element becomes visible?

后端 未结 9 2030
感情败类
感情败类 2020-11-28 05:36

I am building a toolbar that is going to be included into a page. the div it is going to be included in will default to display:none. Is there a way i can p

9条回答
  •  一整个雨季
    2020-11-28 06:23

    As @figha says, if this is your own web page, you should just run whatever you need to run after you make the element visible.

    However, for the purposes of answering the question (and anybody making Chrome or Firefox Extensions, where this is a common use case), Mutation Summary and Mutation Observer will allow DOM changes to trigger events.

    For example, triggering an event for a elements with data-widget attribute being added to the DOM. Borrowing this excellent example from David Walsh's blog:

    var observer = new MutationObserver(function(mutations) {
        // For the sake of...observation...let's output the mutation to console to see how this all works
        mutations.forEach(function(mutation) {
            console.log(mutation.type);
        });    
    });
    
    // Notify me of everything!
    var observerConfig = {
        attributes: true, 
        childList: true, 
        characterData: true 
    };
    
    // Node, config
    // In this case we'll listen to all changes to body and child nodes
    var targetNode = document.body;
    observer.observe(targetNode, observerConfig);
    

    Responses include added, removed, valueChanged and more. valueChanged includes all attributes, including display etc.

提交回复
热议问题