Shafizadeh
Shafizadeh

Reputation: 10340

why onload event not working?

here is my codes:

$('.classname').on('click',function myfunc() {
  alert ('working ..!');
});

the above code works correctly and when I click on the div .classname, it gives me a message: working ..!

Now I want to use of that function (myfunc) for onload event. here is my try:

window.onload = myfunc;
window.onload = myfunc();
document.onload = myfunc();
<body onload = "myfunc()">
object.onload=myfunc(){alert ('working ..!');}

but none of them does not works. Why ?! Why, when I refresh the page don't see any message ? How can I fix it ?

Upvotes: 2

Views: 2105

Answers (3)

Patrick Ferreira
Patrick Ferreira

Reputation: 2053

what about using ready event instead of load? as you can read in jquery documentation :

.load() Bind an event handler to the “load” JavaScript event.

.ready() Specify a function to execute when the DOM is fully loaded.

In my opinion, the full dom should be fully loaded (ie, size of element already set and computed for scroll...)

function scroll() {
    alert('test');
     return false;
}

$('.link').on('click', scroll);
$(document).on('ready', scroll);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="link">manual test</a>

EDIT Answer for inital post. Carefull, I saw that you put spaces between prop key and value <body onload = "myfunc()"> you can't do this. It should be key=value

var myfunc = function() {
  alert ('working ..!');
}
<body onload="myfunc()">
  <a onclick="myfunc()">manual test</a>
</body>

Upvotes: 0

Quentin
Quentin

Reputation: 943118

$('.classname').on('click',function myfunc() {
  alert ('working ..!');
});

You have created a named function using a function expression. You have passed it to on().

Because it is a function expression, you are not creating a variable called myfunc in the current scope. It is accessible only from inside itself, and from within the on function.

Use a function declaration instead.

function myfunc() {
  alert ('working ..!');
}
$('.classname').on('click', myfunc);
$(document).on('load', myfunc);

Further reading on function declarations and expressions can be found on MDN.

Upvotes: 2

Kaspersky
Kaspersky

Reputation: 95

The scope of the function is not global so you need to declare it outside the click event.

Upvotes: 0

Related Questions