I want to put this in my website
<script type="text/javascript"> <!-- window.onload = hello; function
hello() { var name = prompt("What is your name", "") alert ( "Hello "
+ name + "! Welcome to my forum.") } </script>
but I dont want to put it in index but in separate file, let say hello.js
How can I call it from index file so when I click the index.html, it will immediately prompt for my name. (for example)
I put <script src="hello.js"></script>
does not work.
To call a function on page load, use −. window.onload Example. You can try to run the following code to implement a JavaScript function on page load. Live Demo <!DOCTYPE html> <html> <body> <script> function alertFunction() { alert('ok'); } window.onload = alertFunction; </script> </body> </html>
script.innerHTML = 'alert ("Inline script loaded!")' As you can see, it’s easy to create and append new script elements, allowing us to include any number of external JavaScript files dynamically after a page has loaded. The real challenge isn’t loading the file – it’s knowing when the file has finished loading.
It increases the code re usability. <script type="text/javascript" src="external.js"></script> First create a JavaScript file and then save the file with .js extension. After that we can use src attribute of script tag to use this already created file. function show () { alert ("External JavaScript file."); }
When using JavaScript, sometimes you will run into errors because the external code being used is placed above the HTML it is calling/manipulating. For this example, we have a HTML file that looks like this:
Your hello.js should look something like this:
window.onload = hello;
function hello() {
var name = prompt("What is your name", "");
alert("Hello " + name + "! Welcome to my forum.");
}
and then the <script src="hello.js"></script>
should work just fine.
There shouldn't be much more to it than importing that script. But then, your script is all broken. Of course it won't work, unless your browser can interpret it. Take a look at javascript basics. On the first look, you don't seem to be using semicolons to delimit individual statements. Also, you have opened an HTML comment <!--
but you have never closed it...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With