tatty27
tatty27

Reputation: 1554

Can I run more than one javascript onload?

I have a page that uses modernizr.js which runs when the page loads up. Before I added this I had a simple js clock script running to display the time which also loaded when the page loaded, however, since adding both of them to the page at the same time makes one or the other stop working.

I am still fairly new to javascript and am getting to grips with the rules (self taught). Is it possible to ave two scripts running on load and if so how? Or, am I barking up the wrong tree and if so is there something wrong with my code?

This is what I had...

<script>
window.onload = function() {
   if(window.FileReader && Modernizr.draganddrop){
      window.location = "http://www.dentaldigs.co.uk/image_upload.php"

   }
};
</script>

<script>
      // add a zero in front of numbers<10
      function checkTime(i)
      {
      if (i<10)
        {
          i="0" + i;
        }
      return i;
      }

      function clock()
      {
      var today=new Date();
      var h=today.getHours();
      var m=today.getMinutes();
      var s=today.getSeconds();
      m=checkTime(m);
      s=checkTime(s);
      document.getElementById('clock_div').innerHTML=h+":"+m+":"+s;
      t=setTimeout(function(){clock()},500);
      }  

</script>

<body onLoad="clock()">
</body>

With the clock script in place the modernizr.js doesn't work.

Thanks

Upvotes: 1

Views: 220

Answers (3)

AvL
AvL

Reputation: 3093

Why don't you simply add clock(); to window.onload right after calling the Modernizr script:

<script>
window.onload = function() {
   // loading modernizr
   if(window.FileReader && Modernizr.draganddrop){
      window.location = "http://www.dentaldigs.co.uk/image_upload.php"
   }
   // calling your clock script
   clock();
};
</script>
<body>
   ...
</body>

Upvotes: 2

elkebirmed
elkebirmed

Reputation: 2357

use this one

function myFunctions() {
  function1();
  function2();
}
window.onload = myFunctions;

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227200

Instead of assigning directly to window.onload, you should bind events using addEventListener. That way you can assign multiple functions.

window.addEventListener('load', function(){
    console.log('first onload');
});

window.addEventListener('load', function(){
    console.log('second onload');
});

DEMO: http://jsfiddle.net/jjqCX/

UPDATE: If you are using IE < 9, you need to use attachEvent.

function loaded = function(){
    console.log('first onload');
}

function loaded2 = function(){
    console.log('second onload');
}

if (window.addEventListener) {
    window.addEventListener('load', loaded, false); 
    window.addEventListener('load', loaded2, false); 
}
else if (window.attachEvent)  {
    window.attachEvent('onload', loaded);
    window.attachEvent('onload', loaded2);
}

DEMO: http://jsfiddle.net/jjqCX/1/

Upvotes: 2

Related Questions