Raja
Raja

Reputation: 792

Call <body onload="function()"> in javascript file

I've called two functions in my HTML

<body onload="myFunction()" onmousemove="myFunction1()">

I want to execute these two functions from a javascript file and call this file in my HTML like

<script type="text/javascript" src="path/to/functions.js"></script>

i.e. both the functions will be called from the javascript file, not from html.

I have tried

window.addEventListener('load', myFunction()); window.addEventListener('onmousemove', myFunction1());

or

$(window).load(function () {
    myFunction(); 
});
$(window).onmousemove(function () {
    myFunction1(); 
});

but failed.

What should I do ?

DETAILS

I have a javascript file where some functions are there.

script.js

function myFunction() {
     alert("This is my function");
}

function myFunction1() {
     alert("This is my second function");
}

I called these functions in my html body tag

<body onload="myFunction()" onmousemove="myFunction1()">

Now I want to call these two functions from my script.js like

window.addEventListener('load', myFunction());
 window.addEventListener('onmousemove', myFunction1());

what should I do ?

I think you have understood my requirement.

Upvotes: 0

Views: 3951

Answers (3)

Vikrant Kashyap
Vikrant Kashyap

Reputation: 6846

I think You should verify that your (.js) file is loaded with the page or not? Because i have tried both the example and both r working window.addEventListener('load', myFunction); and window.addEventListener('load', myFunction());

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
    alert("Page is loaded");
}
window.addEventListener('load', myFunction);
</script>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>

or

<!DOCTYPE html>
    <html>
    <head>
    <script>
    function myFunction() {
        alert("Page is loaded");
    }
    window.addEventListener('load', myFunction());
    </script>
    </head>
    <body>
    <h1>Hello World!</h1>
    </body>
    </html>

Upvotes: -1

Tornike Shavishvili
Tornike Shavishvili

Reputation: 1354

Your code should read like this:

window.addEventListener('load'      , myFunction  );
window.addEventListener('mousemove' , myFunction1 );

But if it still does not work for you, Try this:

window.onload      = myFunction  ;
window.onmousemove = myFunction1 ;

Check this: onload and this: onmousemove

Upvotes: 5

Try

function number1(){
    document.querySelector("#info").innerHTML = "LOAD";
  }
  
  function number2(){
    var x = event.clientX;
    var y = event.clientY;

   document.querySelector("#info").innerHTML = "MouseMove: ( x:"+x+" , y:"+y+") ";
  }
  
    window.onload = function(){
   number1()
   }
    
   window.onmousemove = function(){
   number2()
   }
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<div id="info">waiting</div>
</body>
</html>

Upvotes: 0

Related Questions