-1

Why my function not alert when load page [javascript]?

When scroll page it's alert work good.

When resize page it's alert work good.

But when load page why not alert ?

How can i do that ?

http://jsfiddle.net/af2kgoxu/

$(window).load(function(){
    $(window).on('scroll load resize', function () {
        alert("TEST");
    });
});

5 Answers5

2

I'm pretty sure because load happened before you created the listener. Think about it:

$(window).load(function(){ When the window is loaded, do the next step:

$(window).on('scroll load resize', function () { creates a listener on scroll, load, and resize. Well the window already loaded so it's never going to load again.

$(document).ready(function(){
    $(window).on('scroll load resize', function () {
        alert("TEST");
    });
});
Leeish
  • 5,153
  • 2
  • 16
  • 42
  • Per http://stackoverflow.com/questions/3520780/when-is-window-onload-fired the window is loaded after the DOM so to keep your exact code just use the DOM ready from jQuery and it'll work, but @nikhil has an answer too. Not sure if there is an actual difference between mine and his and if any blocking occurs with his vs mine or anything. Probably not. – Leeish Jun 19 '15 at 18:12
1

Why you are wrapping your scroll,load, resize operations in $(window).load(function(){}); when you can directly call it. Change your snippet as below, it will work for all window scroll,load and resize.

$(window).on('scroll load resize', function () {
    alert("TEST");
});
Arpit Aggarwal
  • 24,784
  • 14
  • 83
  • 102
0

You can always try

$(window).on('load',function()

But i think its the same

Henrique Alves
  • 37
  • 1
  • 1
  • 9
0

You just need this code:

$(window).on('scroll load resize', function () {
alert("TEST");
});

See here: http://jsfiddle.net/af2kgoxu/1/

JGV
  • 4,847
  • 8
  • 43
  • 87
0

Use $( document ).ready() method, and it will run whenever your DOM (Document Object Model) is ready for running javascript.

    $( document ).ready(function() {
        alert("TEST");
    });
Prasad Lakmal
  • 139
  • 1
  • 9