Jump to content

External JavaScript isn't working.


Trick_Master990

Recommended Posts

Hey guys, I'm new to JavaScript and right now I'm having trouble changing element using external JS

 

This is the HTML code:

 

<head>
<script src="myscript.js" type="text/javascript"></script>
</head>
<body>
<p id="demo"></p>
</body>
------------------------------------------------------------------------------------
This is the JS code:
window.alert("Hello World");
document.getElementById("demo").innerHTML = "Hello World!";
I only got the alert line of code working and not innerHTML. I wonder why?

 

Link to comment
Share on other sites

Try adding <script src="myscript.js" type="text/javascript"></script> after <p id="demo"></p> and it should work. The script runs before the html page finishes loading.

 

For your myscript.js file to access HTML elements once the page has loaded, add the following to myscript.js and leave the script in the head section of the html page and you should see "Hello World!' in the p elements' innerHTML displayed:

// this assigns a function to the window.onload event and the function runs once the page has loaded.window.onload = function init() {     window.alert("Hello World");     document.getElementById("demo").innerHTML = "Hello World!";}
  • Like 1
Link to comment
Share on other sites

You don't require window. as prefix to alert try

window.onload = function() {     alert("Hello World");     document.getElementById("demo").innerHTML = "Hello World!";}

you could run a init() function with

window.onload =  init;function init(){     alert("Hello World");     document.getElementById("demo").innerHTML = "Hello World!";}
Link to comment
Share on other sites

Those messages are all just code style and formatting messages, they aren't errors. JSLint messages are typically not syntax errors with the code, it just tries to force you to use a specific coding style.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...