Joe Knight Joe Knight - 6 months ago 10
HTML Question

Manipulating images via javascript, very simple

edit:

thanks a lot ya'll. Have a great night/day




All I'm trying to do is have javascript change the image src in a table cell by checking the id of the cell.

I have looked at every single related question on stack overflow and their solution. For some reason, my code won't work. Most likely syntax/lack of sleep issue

This js script in a table, located right above the src I'm trying to change depending on things:

<script>
function getImage(){
return "http://i.imgur.com/s5WKBjy.png"; //i literally just want to see if this works and it isn't
}
document.onload = function(){
document.getElementById('homeimage').src = getImage();
};
</script>

<td colspan="3"><img style="width:110px;height:128px;" id = "homeimage" onload="getImage()"></td>


<td colspan = "3"><img style="width:150px;height:128px;" id = "homeimage"></td>


neither of the above work. With the onload = "getImage()" and without. Am I being dumb? There's got to be something obvious I'm missing.

Answer

We can't use same id more than once in a single web page. Use different ids. 2nd change doucment.onload to window.onload

function getImage(){  
 return "http://i.imgur.com/s5WKBjy.png";
}  
window.onload = function(){  
    document.getElementById('homeimageA').src = getImage();
    document.getElementById('homeimageB').src = getImage();
}
  <td colspan="3"><img style="width:110px;height:128px;" id = "homeimageA" onload="getImage()"></td>   


 <td colspan = "3"><img style="width:150px;height:128px;" id = "homeimageB"></td>