0

I am trying to set an image dynamically at runtime using javascript. However i always get 404 error in firebug saying image could not be found. when i run this the javascript seems to look for the image in the Home Folder rather than the image folder. Am i missing a format to specify the image urls?
Why is it looking at that location whereas it should be looking at Images folder in the solution? Also if i make that javascript external the html cannot access it even though my references to the js file are correct. Anyone willing to contribute on this? you help be very much appreciated.

Here is my code

Html

<body onload="startTime();">   

        <div class="img">
             <img id="img1" border="0" src="~/Images/Ghandrukpic4.jpg" alt="GhanddrukPic4" class="image" />
        </div>         

</body>

Javascript Code

    $(function () {

        function startTime() {

        var imgArray = new Array("Images/60987Ghandruk Village.jpg", "Images/GhandrukPic2.jpg", "Images/ghandrukpic3.jpg");
        var imgCount = 0;
        if (imgCount == imgArray.length) {
            imgCount = 0;
        }
        document.getElementById("img1").src = imgArray[imgCount];
        imgCount++;
        setTimeout("startTime()", 5000);
    }

});

1 Answer 1

1

add a / in front of your Images string in the array.

new Array("/Images/60987Ghandruk Village.jpg", "/Images/GhandrukPic2.jpg", "/Images/ghandrukpic3.jpg");

This will let the browser know to request from the root directory of your site. If there is no forward slash it is a Relative path to the page that is loaded. So if the page you are on is http://yoursite.com/home/ then it will be looking in the images directory nested in your nonexistant /home directory.

As far as your javascript. Unwrap your startTime function like so in your external and it should work fine.

function startTime() {

        var imgArray = new Array("/Images/60987Ghandruk Village.jpg", "/Images/GhandrukPic2.jpg", "/Images/ghandrukpic3.jpg");
        var imgCount = 0;
        if (imgCount == imgArray.length) {
            imgCount = 0;
        }
        document.getElementById("img1").src = imgArray[imgCount];
        imgCount++;
        setTimeout("startTime()", 5000);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome :) Thank you very much @Bluetoft you are a magician :)

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.