0

I want to load/replace an image at a defined location. It works with "onclick" but it doesn't work with "onload". It seems to be linked with the problem CORS (I use firefox), but I don't know how to change in my code.

The html code works well with:

<img id="demo" onclick="loadImg()" src="css/images/movie5.jpg"  width="100" height="232">

But it doesn't work with:

<img id="demo" onload="loadImg()" src="css/images/movie5.jpg"  width="100" height="232">

Where my function loadImg():

<script>
function loadImg() {
      document.getElementById("demo").src = "css/images/movie2.jpg";
}
</script>

Someone can give me a solution?

gogo
  • 11
  • 1
  • Don't use inline `style` or `on*` attributes. Start using https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener - Styles or scripts should be easily debuggable and inside in their respective files or tags. Not disseminated around your document markup :) – Roko C. Buljan Mar 28 '21 at 02:41
  • this is because the image load event come before the script is loaded. when the js script becomes operational it waits for an event that no longer exists – Mister Jojo Mar 28 '21 at 02:45
  • 1
    @RokoC.Buljan, this is just a test. I have to do a project with a given local API REST Django. The goal is to built a web which displays film images by categories. For my first idea, I have to built a pattern of images by category, for example, 4 images per category. They are empty images at first. Then after doing the request with my API, I have the image urls, I will load them on pre-defined location (my pattern of categories). I don't know if it is a good idea to do my project? Have you got other idea about steps for building my web? Thank a lot. – gogo Mar 28 '21 at 10:05
  • @MisterJojo, I tried by adding the following code: `` and it works. I think it is really related to CORS problem but I don't know what I did is correct. – gogo Mar 28 '21 at 10:17
  • this is not a CORS problem, this a timming question, this code will never work, original image and script code cannot happen in the same time and have a reference of each other. – Mister Jojo Mar 28 '21 at 12:36

1 Answers1

0

The "onload" event is considered as Html Dom. If you would like to run a script through the "onload" event, you have(at least based on my knowledge) to place the script inside the body. Like the following code:

<body>
<img id="demo" onload="loadImg()" src="https://upload.wikimedia.org/wikipedia/en/6/6b/Hello_Web_Series_%28Wordmark%29_Logo.png"  width="400" height="232">
  
 <script>
function loadImg() {
      document.getElementById("demo").src = "https://thumbs.dreamstime.com/b/word-goodbye-handwritten-whiteboard-goodbye-167996758.jpg";
}
</script>
</body>

You can also look into questions that are asked before:

an onload even outside of the body tag?

Is it wrong to place the tag after the tag?