-2

Please answer this question, as I am struggling a lot with it.

I am trying to change image source on mouse over. I am able to do it, but image is not displaying on page.

I am trying to change image source to cross domain URL. I can see that in DOM image source is changing but on page its not.

I have tried all solutions mentioned in LINK, but none of them is working. Please let me solution to problem.
NOTE:

  1. I can see in network tab image is taking some time to download (about 1 sec).
  2. It is an intermediate issue, sometime image is loading and sometimes its not

CODE:

 document.getElementsByTagName('img')[0].addEventListener('mouseover', function() 
{
    document.getElementsByTagName('img')[0].setAttribute('src', 'url/of/the/image');
});
Tavish Aggarwal
  • 1,020
  • 3
  • 22
  • 51

3 Answers3

0

have you tried loading images before everything else?

function initImages(){
    var imC = 0;
    var imN = 0;
    for ( var i in Images ) imN++;
    for(var i in Images){
        var t=Images[i];
        Images[i]=new Image();
        Images[i].src=t;
        Images[i].onload = function (){ 
            imC++; 
            if(imC == imN){
                console.log("Load Completed");
                preloaded = 1;
            }
        }
    }

}

and

var Images = {
    one image: "path/to/1.png",
    ....
}

then

if( preloaded == 1 ){
    start_your_page();
}
Amber
  • 113
  • 1
  • 8
  • I am getting images from service call, and this call is on mouseover.. So at time of page load I dont know the set of images that I have. – Tavish Aggarwal Oct 17 '17 at 07:14
0

Here the code that will remove the img tag and replace it with a new one:

document.getElementsByTagName('img')[0].addEventListener('mouseover', function() {
  var parent = document.getElementsByTagName('img')[0].parentElement;
  parent.removeChild(document.getElementsByTagName('img')[0]);
  var new_img = document.createElement("img");
  new_img.src = "https://upload.wikimedia.org/wikipedia/commons/6/69/600x400_kastra.jpg";
  parent.appendChild(new_img);
});
<img src="https://www.w3schools.com/w3images/fjords.jpg">
Karan Dhir
  • 731
  • 1
  • 6
  • 24
0

I resolved the issue using code:

function displayImage() {
    let image = new image();
    image.src="source/of/image/returned/from/service";
    image.addEventListener('load', function () { 
        document.getElementsByTagName('img')[0].src = image.src;
    },false);
}

Here in code, I am attaching load event to image, source of image will be changed after image is loaded.

Tavish Aggarwal
  • 1,020
  • 3
  • 22
  • 51