Add two functions to window.onload

JavascriptFunction

Javascript Problem Overview


I have two functions on my form except one does not work if the other is active. Here is my code:

window.onload = function(event) {
    var $input2 = document.getElementById('dec');
    var $input1 = document.getElementById('parenta');
    $input1.addEventListener('keyup', function() {
        $input2.value = $input1.value;
    });
}

window.onload=function(){
    document.getElementById('enable').onchange=function(){
        var txt = document.getElementById('gov1');
        if(this.checked) txt.disabled=false;
        else txt.disabled = true;
    };
};

What I mean is that when I have both these functions in my form the second function works fine but the first will not work, if take out the second function the first one will work like normal, why is this happening? Is it because of the names?

Javascript Solutions


Solution 1 - Javascript

window.addEventListener("load",function(event) {
    var $input2 = document.getElementById('dec');
    var $input1 = document.getElementById('parenta');
    $input1.addEventListener('keyup', function() {
        $input2.value = $input1.value;
    });
},false);

window.addEventListener("load",function(){
    document.getElementById('enable').onchange=function(){
        var txt = document.getElementById('gov1');
        if(this.checked) txt.disabled=false;
        else txt.disabled = true;
    };
},false);

Documentation is here

Note that this solution may not work across browsers. I think you need to rely on a 3-rd library, like jquery $(document).ready

Solution 2 - Javascript

If you can't combine the functions for some reason, but you have control over one of them you can do something like:

window.onload = function () {
    // first code here...
};

var prev_handler = window.onload;
window.onload = function () {
    if (prev_handler) {
        prev_handler();
    }
    // second code here...
};

In this manner, both handlers get called.

Solution 3 - Javascript

Try putting all you code into the same [and only 1] onload method !

 window.onload = function(){
        // All code comes here 
 }

Solution 4 - Javascript

You cannot assign two different functions to window.onload. The last one will always win. This explains why if you remove the last one, the first one starts to work as expected.

Looks like you should just merge the second function's code into the first one.

Solution 5 - Javascript

window.addEventListener will not work in IE so use window.attachEvent

You can do something like this

function fun1(){
    // do something
}

function fun2(){
    // do something
}


var addFunctionOnWindowLoad = function(callback){
      if(window.addEventListener){
          window.addEventListener('load',callback,false);
      }else{
          window.attachEvent('onload',callback);
      }
}

addFunctionOnWindowLoad(fun1);
addFunctionOnWindowLoad(fun2);

Solution 6 - Javascript

Because you're overriding it. If you want to do it with onload you could just extend the previous function. Here's one way to do it:

Function.prototype.extend = function(fn) {
  var self = this;
  return function() {
    self.apply(this, arguments);
    fn.apply(this, arguments);
  };
};

window.onload = function() {
  console.log('foo');
};

window.onload = window.onload.extend(function() {
  console.log('bar');
});

// Logs "foo" and "bar"

Demo: http://jsbin.com/akegut/1/edit

Edit: If you want to extend with multiple functions you can use this:

Function.prototype.extend = function() {
  var fns = [this].concat([].slice.call(arguments));
  return function() {
    for (var i=0; i<fns.length; i++) {
      fns[i].apply(this, arguments);
    }
  };
};

window.onload = window.onload.extend(function(){...}, function(){...}, ...);

Solution 7 - Javascript

If you can not access to the old window.onload yet still want to keep and add another one, here is the way,

       function addOnload(fun){
		  var last = window.onload;
		  window.onload = function(){
			if(last) last();
		    fun();
		  }
		} 

        addOnload(function(){
			console.log("1");
		});

		addOnload(function(){
			console.log("2");
		});
		

Solution 8 - Javascript

Simply Use (jQuery):

$(window).load(function() {
  //code
})

$(window).load(function() {
 //code
})

Solution 9 - Javascript

For some time I used the above solution with:

window.onload = function () {
    // first code here...
};

var prev_handler = window.onload;
window.onload = function () {
    if (prev_handler) {
        prev_handler();
    }
    // second code here...
};

However it caused in some cases IE to throw a "stack overflow error" described here in this post: https://stackoverflow.com/questions/226102/stack-overflow-in-line-0-on-internet-explorer and a good write-up on it here

After reading through all the suggested solutions and having in mind that jquery is not available, this is what I came up with(further expanding on Khanh TO's solution with some browser compatibility checking) do you think such an implementation would be appropriate:

function bindEvent(el, eventName, eventHandler) {
			if (el.addEventListener){
					el.addEventListener(eventName, eventHandler, false); 
				} else if (el.attachEvent){
					el.attachEvent("on"+eventName, eventHandler);
				}
			}
      render_errors = function() {
      //do something
      }
      
      bindEvent(window, "load", render_errors);
      
      render_errors2 = function() {
      //do something2
      }

      bindEvent(window, "load", render_errors2);

Solution 10 - Javascript

By keeping 2 window.onload(), the code in the last chunk is executed.

Solution 11 - Javascript

Why not just call both functions from one onload-function?

function func1() {
	// code
}

function func2() {
	// code
}

window.onload = function() {
	func1();
	func2();
}

Solution 12 - Javascript

When you put the second function into window.onload basically what you are doing is replacing a value. As someone said before you can put the two functions into one function and set window.onload to that. If you are confused think about it this way, if you had an object object, and you did object.value = 7; object.value = 20 the value would be 20 window is just another object

Solution 13 - Javascript

You can not bind several functions to window.onload and expect all of these functions will be executed. Another approach is using $(document).ready instead of window.onload, if you already use jQuery in your project.

Solution 14 - Javascript

If you absolutely must have separate methods triggered as the result of window.onload, you could consider setting up a queue of callback functions which will be triggered.

It could look like this in its simplest form:

var queue = [];
var loaded = false;

function enqueue(callback)
{
	if(!loaded) queue.push(callback);
	else callback();
}

window.onload = function()
{
    loaded = true;
	for(var i = 0; i < queue.length; i++)
	{
		queue[i]();
	}
}

And used in your case like so:

enqueue(function()
{
	var $input2 = document.getElementById('dec');
	var $input1 = document.getElementById('parenta');
	$input1.addEventListener('keyup', function()
	{
		$input2.value = $input1.value;
		
	});

});

enqueue(function()
{
	document.getElementById('enable').onchange=function()
	{
	    var txt = document.getElementById('gov1');
	    if(this.checked) txt.disabled=false;
	    else txt.disabled = true;
	};

});

Solution 15 - Javascript

this worked for me

function first() {
    console.log(1234);
}

function second() {
    console.log(5678);
}

const windowOnload = window.onload = () => {
    first();
    second();
};

windowOnload();

console

1234

5678

Solution 16 - Javascript

I didn't like other answers and found another way of doing this.

This can be achieved with this function.
readyState has 3 options loading, interactive and complete https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState

Therefore, this script would work:

<script>
  if (typeof whenDocReady === "function") {
    // already declared, do nothing
  } else {
    function whenDocReady(fn) {
      // see if DOM is already available
      if (document.readyState === "complete" || document.readyState === "interactive") {
        // call on next available tick
        setTimeout(fn, 1);
      } else {
        document.addEventListener("DOMContentLoaded", fn);
      }
    }
  }
</script>

Usage after defining this script:

<script>
whenDocReady(function() {
//do whatever stuff what you would do on window.onload
};
</script>

Credit: https://stackoverflow.com/a/9899701/1537394

Solution 17 - Javascript

using promises:

    function first(){
          console.log("first");
    }

    function second(){
          console.log("second");
    }
    
    isLoaded = new Promise((loaded)=>{ window.onload = loaded });
    isLoaded.then(first);
    isLoaded.then(second);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAJJView Question on Stackoverflow
Solution 1 - JavascriptKhanh TOView Answer on Stackoverflow
Solution 2 - JavascriptchadView Answer on Stackoverflow
Solution 3 - JavascriptJanakView Answer on Stackoverflow
Solution 4 - JavascriptLeniel MaccaferriView Answer on Stackoverflow
Solution 5 - Javascriptrohit vermaView Answer on Stackoverflow
Solution 6 - JavascriptelclanrsView Answer on Stackoverflow
Solution 7 - JavascriptserkanView Answer on Stackoverflow
Solution 8 - JavascriptSebastien HorinView Answer on Stackoverflow
Solution 9 - JavascriptTsonevView Answer on Stackoverflow
Solution 10 - JavascriptSadhanaPView Answer on Stackoverflow
Solution 11 - Javascriptdas KeksView Answer on Stackoverflow
Solution 12 - JavascriptaaronmanView Answer on Stackoverflow
Solution 13 - JavascriptXiaodan MaoView Answer on Stackoverflow
Solution 14 - JavascriptMartyView Answer on Stackoverflow
Solution 15 - JavascriptAdamView Answer on Stackoverflow
Solution 16 - JavascriptMladen AdamovicView Answer on Stackoverflow
Solution 17 - Javascriptuser8481047View Answer on Stackoverflow