Reputation: 2193
I'm trying to switch an image on a HTMLbutton using javascript.
It works, but I think it loads the image every time I click the button, and that's not good. So I want to load the images only one time and than I can switch between the images. This Is what I have now.
mute.onclick=function () {
if (audioEngine.isMuted)
{
document.getElementById('muteIcon').src="images/unmuted.png";
}
else{
document.getElementById('muteIcon').src="images/unmuted.png";
}
But I think every time I click the button it looks in the path "images/unmuted.png" to see what's there and load it. So I was thinking this is an easy fix. I just define a variable unmuteImage and assign that to document.getElementById('muteIcon').src. Like this
var unmuteImage=new Image();
unmuteImage.src='images/unmuted.png';
mute.onclick=function () {
if (audioEngine.isMuted)
{
document.getElementById('muteIcon').src=unmuteImage;
}
else{
document.getElementById('muteIcon').src="images/unmuted.png";
}
But when I do this, I get the following error in my consols:
GET file:///path/to/the/mian/html/file/[object%20HTMLImageElement] (In red text)
And I don't get the image, I get the "borken image" picture because somehow it didn't find the picture.
Can somebody help me please? Thanks
Upvotes: 0
Views: 128
Reputation: 386
this may work for you if you have jquery
$('#muteIcon').replaceWith(unmuteImage);
other wise you have to use src itself
document.getElementById('muteIcon').src = unmuteImage.src;
Upvotes: 1