Javascript - Switching Between Two Images

html, image, javascript

Solution

You are using assign operator instead of comparison operator. Also use `else if` or just `else` in the second condition.

Change to

if (url == 'Resources/Share1.bmp')

and

else if (url == 'Resources/Share2.bmp')

and it should work.

See this DEMO to help you with. It toggles the image with 2 seconds interval

Problem

I have the following Javascript code which should rapidly switch between two images: ``` <head runat="server"> <title>Home Page</title> <script src="Resources/jQuery.js" type="text/javascript"></script> <script type="text/javascript"> function changeImage() { requestAnimationFrame(changeImage); var url = document.getElementById('Change_Image').src; if (url == 'Resources/Share1.bmp') { document.getElementById('Change_Image').src = 'Resources/Share2.bmp'; } else { if (url == 'Resources/Share2.bmp') { document.getElementById('Change_Image').src = 'Resources/Share1.bmp'; } } } </script> </head> <body> <form id="form1" runat="server"> <div> <h1>Welcome to my Website</h1> <h2>Below you can find an example of visual cryptography</h2> <br /> <br /> <div><img id="Change_Image" src="Resources/Share1.bmp" alt="Letter A" /></div> </div> </form> </body> </html> ``` Unfortunately, the code does not work and the image does not change to another one. What am I doing wrong? I am quite new to JavaScript so bear with me please?

Original source