Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Switching Between Two Images

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?

like image 854
Matthew Avatar asked Oct 16 '25 14:10

Matthew


1 Answers

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

like image 99
letiagoalves Avatar answered Oct 18 '25 07:10

letiagoalves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!