first off I have both my JavaScript and my html files in the same folder. I cannot understand why none of my javascript works in the html file.
I have tried putting the Script directly into the html file without sourcing the Script file. I have attempted 3 different ways of adding my function to the html file to no avail. I am trying to make a hangman game for practice because I figured it was probably the easiest thing to try after going thru all the classes I took. However, I cannot even get through testing if my JavaScript even works. I’ll let the code speak for itself. (this JS code is within the body of the html file if that helps. Obviously, I do have script type="txt/javascript" src="hangman.js" JS tags at the bottom of my html body)
1st try:
html:
<div id="game">
<button id="testA" onclick="showWord()">show word</button>
<p id="word"></p>
</div>
external JS file code:
function showWord() {
document.getElementById("word").innerHTML = "test";}
2nd try:
html:
<div id="game">
<button id="testA">show word</button>
<p id="word"></p>
</div>
external JS file code:
function showWord() {
document.getElementById("testA").addEventListener("click", function(){
document.getElementById("word").innerText = "test";}
after this, I tried adding this code directly to the script tag and omitted the external script and still no luck. I also tried adding the onclick attribute to the html file with this with no change.
3rd try:(tried saving the element selection to a global variable here in case that was the problem)
html:
<div id="game">
<button id="testA" onclick="showWord()">show word</button>
<p id="word"></p>
</div>
external JS file code:
const test = document.querySelector("#word");
function showWord() {
test.innerHTML = "try 3";
}
still… no change… please help!
2
Answers
Your first try should have worked. Was your browser actually re-loading your page? If it was using a cached version of the page, and you hadn’t finished your code by adding the script, you would see the previous behavior of the page. To check what is loaded in chrome, you can use f12 to view the page and see if it matches your latest changes.
see: https://alphaefficiency.com/how-does-browser-caching-affect-web-design
Your second try does not appear to ever call showWord. You have the creation of the listener inside the function you want the listener to call.
If you’re adding the script via a tag that looks like:
It will not work.
The documentation for the
<script>
element notes:And the valid MIME type for javascript is
text/javascript
among others, nottxt/javascript
.