Upload Image via javascript

3

I tried to upload image by JS but I could not do it through onload , it follows the code I tried:

HTML:

<img  class="razer" id="imageoption" onload="imageOption()">

JS:

document.onload = function imageOption() {
document.getElementById("imageoption").src = "images/hyperx-option.png"; }  
    
asked by anonymous 16.02.2018 / 19:32

4 answers

2

The event onload can not be accessed by document it has to be accessed directly by window , as shown in the code below.

window.onload = function imageOption() {
    document.getElementById("imageoption").src = "images/hyperx-option.png";
}

Some of the JavaScript events are only accessible by window , as well as onload .

    
16.02.2018 / 19:48
2

Another solution using Jquery

<img  class="razer" id="imageoption">

Script:

$(document).ready(function(){
     $('#imageoption').attr('src','images/hyperx-option.png');
   });

Once the document is loaded, it will assign the src fined% to the image.

    
16.02.2018 / 20:37
0

The function in onload="imageOption()" will never be called with src empty. The onload is fired just when something is loaded. With src empty, this something is non-existent.

What you can do is to change src of the image when the DOM is ready:

document.addEventListener("DOMContentLoaded", function(){
   document.getElementById("imageoption").src = "https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg";
});
<img src="" class="razer" id="imageoption">
    
16.02.2018 / 21:06
-1

Javascript

function imageOption(){
   document.getElementById("imageoption").src = "images/hyperx-option.png";
}

HTML

<body onload="imageOption()">
<img  class="razer" id="imageoption" src="" />

If you want the image to be dynamically changed by JavaScript use setTimeout within the end of the function:

function imageOption(){
   document.getElementById("imageoption").src = ; // coloque a variável das condições que vai mudar a imagem
   setTimeout(function(){ imagemOption(); }, 10000); //intervalo de 10 segundos
}
    
16.02.2018 / 21:27