Adding an event listener to an element that doesn't exist yet in vanilla javascript

前端 未结 4 2323
我在风中等你
我在风中等你 2021-02-18 16:23

In JQuery I can do:

$(document).on(\"click\",\"a.someBtn\",function(e){
    console.log(\"hi\");
});

to add an event listener to an element th

4条回答
  •  野的像风
    2021-02-18 16:41

    What you want is to use DOM MutationObserver Events to apply the addEventListener. This DOM API is available on all major browser since 2012 I think.

    I use this on to lower the google translator bar created by their snippet (https://www.w3schools.com/howto/howto_google_translate.asp). Since it creates the element dynamically (an iframe), it is the same problem you have. Just change the callback function and variables for your need.

    //Observer for Google translator bar creation and action to move to bottom
    // Select the nodetree that will be observed for mutations
    var nodetree = document.getElementsByTagName("body")[0];
    // Select the target node atributes (CSS selector)
    var targetNode = "iframe.goog-te-banner-frame";
    // Options for the observer (which mutations to observe)
    var config = { attributes: false, childList: true };
    // Callback function to execute when mutations of DOM tree are observed
    var lowerGoogleTranslateBar = function(mutations_on_DOMtree) {
        for(var mutation of mutations_on_DOMtree) {
            if (mutation.type == 'childList') {
                console.log(mutation);
                if (document.querySelector(targetNode) != null) {
                    //40px is the height of the bar
                    document.querySelector(targetNode).style.setProperty("top", "calc(100% - 40px)");
                    //after action is done, disconnect the observer from the nodetree
                    observerGoogleTranslator.disconnect();
                }
            }
        }
    };
    // Create an observer instance linked to the callback function
    var observerGoogleTranslator = new MutationObserver(lowerGoogleTranslateBar);
    // Start observing the target node for configured mutations
    observerGoogleTranslator.observe(nodetree, config);
    

    You can learn more about this here: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

提交回复
热议问题