Tuesday, 9 May 2017

How to link JavaScript file to HTML

I am creating a very simple HTML file and I am trying to link it to a JavaScript file so that the text changes when I click on it.




I have copied it almost entirely from W3 and it works when I place the javascript code within the HTML script tags, but when I try to source it using the script tags (see the first example below) I am not able to get the JavaScript file to link to the HTML.



Any help you can give me is appreciated. I am currently using Visual Studio Code to do this if that gives any hints as to what I am doing wrong.



HTML










TextChange



This example uses the HTML DOM to assign an "onclick" event to a p element.


Click me.







JavaScript



document.getElementById("demo").onclick = function() {myFunction()};

function myFunction() {
document.getElementById("demo").innerHTML = "YOU CLICKED ME!";
}



Alternate HTML that works









TextChange



This example uses the HTML DOM to assign an "onclick" event to a p element.


Click me.







When I render the HTML and view the source and click on the .js extension, I am able to view the javascript file. Despite this, the text that I want to change when I click on it does not change if I click on it.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...