1

Why the window onload code doesn't work;

window.onload = function(){
    var pix = 5;
     alert(pix)
};

I also tried with global variable

var pix;
window.onload = function(){
    pix = 5;
    alert(pix);
};

The above two code doesn't alert anything

suppose i put alert outside it alerts "undefined"

I expect alert should give 5; Anybody explain what does happen here

My Fiddle

E_net4
  • 27,810
  • 13
  • 101
  • 139
  • 1
    Does this happen in `jsfiddle` only? – Tushar Jun 30 '15 at 11:16
  • 1
    Where are you running that code from? If you set an `.onload` handler *after* the onload event has occurred then the handler won't run. Try this: http://jsfiddle.net/us9swrx1/3/ - same thing, except without jsfiddle's default of wrapping the JS in an onload handler of its own. – nnnnnn Jun 30 '15 at 11:18
  • http://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the – messerbill Jun 30 '15 at 11:20
  • [It is working](http://jsfiddle.net/us9swrx1/9/) – ozil Jun 30 '15 at 11:31

2 Answers2

3

If this happens in jsfiddle only, you've used onLoad option to execute your script. This means, your code is already inside onload event. And your onload handler will not work.

To solve this issue, change the script location to No wrap in <head> or <body> from the left options on jsfiddle.

Demo

Tushar
  • 85,780
  • 21
  • 159
  • 179
0

When onfocus doesn't work try

$(document).ready(function(){
    var blah = 4;
    alert(blah);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
omikes
  • 8,064
  • 8
  • 37
  • 50