0

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

2
  • 2
    Put two <img> tags beside eachother, and use the CSS display property to only display the correct image, e.g., when isMuted === true, show one of the img tags, and vice versa. Commented Nov 16, 2013 at 11:33
  • It shouldn't need to load the images each time, they should be cached and it will reuse the cache. Commented Nov 16, 2013 at 12:17

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, the src works! :D but the replaceWith works only one time. it's strange. It stays on muted icon and doesn't go back to unmuted icon. No error. Strange...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.