I am fairly new to JavaScript, though not to programming. My exercise is to have a page that shows an image and allows the user to go to next/previous image by clicking on a button. I want to load the next/previous image from the server on the button click, so the page doesn't have to load all the images into the browser at once.
This version just has a button to go to the next image, and I'm trying to load it with jQuery or AJAX. The page loads the initial "image0", and the JavaScript debugger shows that the onClick event executes and does what I would expect, but the image doesn't change.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
var imageIndex = 0;
var jpgImageName = "image0"
var loadString = "images/" + jpgImageName + ".JPG";
function changeImage()
{
imageIndex++;
if (imageIndex > 2) { imageIndex = 0; }
var locationString = "images/image" + imageIndex + ".JPG";
var loadString = $("<img />").attr('src', locationString);
$("imageSlot").append(loadString);
}
</script>
</head>
<body>
<div id="imageSlot">
<img id="currentImage" src="images/image0.JPG" height="400" alt="image"+imageIndex/>
</div>
<button id="changeImage" onclick="changeImage()">Change Image</button>
</body>
</html>
I got the append function from another Stack Overflow example. I want to replace the current image, and have seen a suggestion to use html() instead of append() for that, but figured I'd try to get this working before I started changing the example.
I've also tried a .load() function on the image itself with just the URL for the next image. That didn't work either, though attempting to show both in the above example seemed likely to confuse people reading the question. But if you want to show me how to solve it that way, or both ways, that'd be great.
imageIndex = (imageIndex + 1) % 3;.