How to add onload event to a div element

前端 未结 24 2244
谎友^
谎友^ 2020-11-22 00:26

How do you add an onload event to an element?

Can I use:

for t

相关标签:
24条回答
  • 2020-11-22 01:01

    I just want to add here that if any one want to call a function on load event of div & you don't want to use jQuery(due to conflict as in my case) then simply call a function after all the html code or any other code you have written including the function code and simply call a function .

    /* All Other Code*/
    -----
    ------
    /* ----At the end ---- */
    <script type="text/javascript">
       function_name();
    </script>
    

    OR

    /* All Other Code*/
    -----
    ------
    /* ----At the end ---- */
    <script type="text/javascript">
     function my_func(){
       function definition;      
    
      }
    
     my_func();
    </script>
    
    0 讨论(0)
  • 2020-11-22 01:02

    The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there.

    0 讨论(0)
  • 2020-11-22 01:02

    I needed to have some initialization code run after a chunk of html (template instance) was inserted, and of course I didn't have access to the code that manipulates the template and modifies the DOM. The same idea holds for any partial modification of the DOM by insertion of an html element, usually a <div>.

    Some time ago, I did a hack with the onload event of a nearly invisible <img> contained in a <div>, but discovered that a scoped, empty style will also do:

    <div .... >
    <style scoped="scoped" onload="dosomethingto(this.parentElement);" >   </style>
    .....
    </div>
    

    Update(Jul 15 2017) - The <style> onload is not supported in last version of IE. Edge does support it, but some users see this as a different browser and stick with IE. The <img> element seems to work better across all browsers.

    <div...>
    <img onLoad="dosomthing(this.parentElement);" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" />
    ...
    </div>
    

    To minimize the visual impact and resource usage of the image, use an inline src that keeps it small and transparent.

    One comment I feel I need to make about using a <script>is how much harder it is to determine which <div> the script is near, especially in templating where you can't have an identical id in each instance that the template generates. I thought the answer might be document.currentScript, but this is not universally supported. A <script> element cannot determine its own DOM location reliably; a reference to 'this' points to the main window, and is of no help.

    I believe it is necessary to settle for using an <img> element, despite being goofy. This might be a hole in the DOM/javascript framework that could use plugging.

    0 讨论(0)
  • 2020-11-22 01:02

    Since the onload event is only supported on a few elements, you have to use an alternate method.

    You can use a MutationObserver for this:

    const trackElement = element => {
      let present = false;
      const checkIfPresent = () => {
        if (document.body.contains(element)) {
          if (!present) {
            console.log('in DOM:', element);
          }
          present = true;
        } else if (present) {
          present = false;
          console.log('Not in DOM');
        }
      };
    
      const observer = new MutationObserver(checkIfPresent);
      observer.observe(document.body, { childList: true });
      checkIfPresent();
    
      return observer;
    };
    
    const element = document.querySelector('#element');
    const add = () => document.body.appendChild(element);
    const remove = () => element.remove();
    
    trackElement(element);
    <button onclick="add()">Add</button>
    <button onclick="remove()">Remove</button>
    
    <div id="element">Element</div>

    0 讨论(0)
  • 2020-11-22 01:02

    Avoid using any interval based methods and use MutationObserver targeting a parent div of dynamically loaded div for better efficiency.

    Here's the simple snippet:

    HTML:

    <div class="parent-static-div">
      <div class="dynamic-loaded-div">
        this div is loaded after DOM ready event
      </div>
    </div>
    

    JS:

    var observer = new MutationObserver(function (mutationList, obsrvr) {
      var div_to_check = document.querySelector(".dynamic-loaded-div"); //get div by class
      // var div_to_check = document.getElementById('div-id'); //get div by id
    
      console.log("checking for div...");
      if (div_to_check) {
        console.log("div is loaded now"); // DO YOUR STUFF!
        obsrvr.disconnect(); // stop observing
        return;
      }
    });
    
    var parentElement = document.querySelector("parent-static-div"); // use parent div which is already present in DOM to maximise efficiency
    // var parentElement = document // if not sure about parent div then just use whole 'document'
    
    // start observing for dynamic div
    observer.observe(parentElement, {
      // for properties details: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit
      childList: true,
      subtree: true,
    });
    
    0 讨论(0)
  • 2020-11-22 01:02

    You can attach an event listener as below. It will trigger whenever the div having selector #my-id loads completely to DOM.

    $(document).on('EventName', '#my-id', function() {
     // do something
    });
    

    Inthis case EventName may be 'load' or 'click'

    https://api.jquery.com/on/#on-events-selector-data-handler

    0 讨论(0)
提交回复
热议问题