Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Friday, February 19, 2016

Add two functions to window.onload

Add two functions to window.onload


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?

Answer by Leniel Macaferi for Add two functions to window.onload


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.

Answer by Janak for Add two functions to window.onload


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

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

Answer by aaronman for Add two functions to window.onload


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

Answer by Khanh TO for Add two functions to window.onload


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

Answer by Xiaodan Mao for Add two functions to window.onload


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.

Answer by elclanrs for Add two functions to window.onload


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

Answer by Marty for Add two functions to window.onload


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;      };    });  

Answer by chad for Add two functions to window.onload


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.

Answer by SadhanaP for Add two functions to window.onload


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

Answer by Tsonev for Add two functions to window.onload


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: "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);  

Answer by user3274814 for Add two functions to window.onload


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);  

Answer by Sebastien Horin for Add two functions to window.onload


Simply Use (jQuery):

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


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.