Question:
Why won't this simple external javascript function work?
Griffin
2016-05-05 13:48:22 UTC
HTML FILE:









EXTERNAL JAVASCRIPTFILE called myScript.js:
function doStuff()
{
getElementById('image').src = "2.jpg";
}
Three answers:
Newms34
2016-05-05 16:00:28 UTC
This is the point at which you should really be using your console. Right-click (ctrl-click on mac) on the page, and pick "inspect element" or press "ctrl-shift-j" (cmd-shift-j on mac) to bring up the dev console. Make sure you're on the 'console' tab, and then look for any error messages. Specifically, you're looking for any '404' errors, which tell you that the browser tried to find a resource in a particular spot, but couldn't.

You should see at least one error: the getElementByIdea method is on the 'document' object, so you need to do:

document.getElementById('image')...



and not just

getElementById('image')....



Fred has a good idea here, but I don't think it's the issue: if you load the script before the rest of the page, the script won't be able to access the DOM elements loaded after it (sort of). However, each time you run your doStuff() function, you're essentially telling the script "hey, look for that element with id 'image' again!", so this shouldn't matter here.

It is, however, generally a good idea to load all scripts that modify the DOM in some way at the END of your page, as Fred describes.
cpcii
2016-05-05 14:07:32 UTC
Try giving the 2.jpg the full path to the image. It doesn't know that 2 is in the same directory.



Try .src = "http://www.yoursite.com/images/2.jpg"
?
2016-05-05 14:11:50 UTC
Move your script link below the rest of your code in the tag, just above the closing tag.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...