Subhajit Das
Subhajit Das

Reputation: 499

how to call a function on load of an element?

I am trying to call a function onload of elements so that I can specify different changes of each elements I am calling the function.

like i have many divs and each and every div has same data-attribure, I am calling all divs with same data-attribute. Each and every div has different html text, I want to call them, when I am loading the page and get those different values. Like in jQuery we call 'each' function. Here I am submitting my html and javascript code... that will draw a clear picture of it.

   <-- html -->
   <div data-attribute="one">
        <span class='value'>1000</span>
   </div>
   <div data-attribute="two">
        <span class='value'>420</span>
   </div>
   <div data-attribute="three">
        <span class='value'>2000</span>
   </div>

   <!---- javascript ---->
    var abc = document.querySelectorAll('[data-attribute]'); 
        for (i= 0; i < abc.length; i++) {
            abc[i].onload = function(){  
            // --------- working well with click / mousemove events -----
               console.log('function called!');
            };
        }

I don't want to use any library or don't want to call the function on element.

P.S. also let me know if there is other option to do the same. Thank you..

Upvotes: 1

Views: 5887

Answers (2)

Hiranmoy Ghatak
Hiranmoy Ghatak

Reputation: 11

Ready and Load are executed upon document object model. So, you cannot call them on a specific element. In this case, you can use set-timeout function after the DOM is ready to change on multiple elements.

Upvotes: 1

Jamiec
Jamiec

Reputation: 136104

You could wait for the entire DOM to load, and perform any actions you require.

window.onload = function(){
    var abc = document.querySelectorAll('[data-attribute]');
    for (i= 0; i < abc.length; i++) {
         var elem = abc[0];
         if(elem.getAttribute("data-attribute") == "one"){
             // do something here
         }
    }
}

You can expand this idea for as many different attributes/elements as you need.

Upvotes: 2

Related Questions