logo Send us mail:
contact@reliancewisdom.com
WhatsApp or call:
+234 (0)808 881 1560
TOGGLE NAVIGATION
Back to All Forum Posts
How to Change Images on Click Using HTML and JavaScript
Ishola Ayinla    May 25, 2017 at 08:56 AM    1    3111
Please I want to create a photo gallery with one image displaying on page-load where by the images will be changing on click. How can I do this using HTML and JavaScript.
Back to All Forum Posts

1 Answer
Ishola Wasiu says...
May 25, 2017 at 10:29 AM

This is all about clicking on PREVIOUS or NEXT button to display images one after the other.

Open a new file and save it as "load_img.htm" then place the following script inside HEAD section of the HTML document:

<script type="text/javascript" > 
<!-- 
myImages=new Array()
myImages[0]="a1.jpg"; 
myImages[1]="a2.jpg"; 
myImages[2]="a3.jpg"; 
myImages[3]="a4.jpg";
myImages[4]="a5.jpg";
myImages[5]="a6.jpg";
imagecounter=myImages.length-1;
i=0;
function first()
{
document.ani.src=myImages[0];
i=0;
}
function previous()
{
if (i>0)
{
i--;
document.ani.src=myImages[i];
}
}
function next()
{
if (i<imagecounter)
{
i++;
document.ani.src=myImages[i];
}
}
function last()
{
document.ani.src=myImages[imagecounter];
i=imagecounter;
}
//--> 
</script>

We start by initializing two global variables imagecounter and i (after the images array) that serve as a counter to the images. After putting the images (a1.jpg, a2.jpg, a3.jpg, a4.jpg, a5.jpg and a6.jpg), we define four functions: first() , previous() , next() and last() that change the source of image with the id imageviewer . The functions are called when the client clicked on the First , the Previous , the Next or the Last button.

Then type in the BODY section:

<div align="center">
<form>
<input type="button" value="First" onclick="first()">
<input type="button" value="Previous" onclick="previous()">
<input type="button" value="Next" onclick="next()">
<input type="button" value="Last" onclick="last()">
</form>
<img id="imageviewer" width="150" height="86" src="a1.jpg" name="ani" alt="'Animated' Jpg">
</div>

You can customize the script and create .jpg slide-shows easily.

Note: These "animated" jpgs will not work browsers that have JavaScript disabled.

Also Note: You must have five(5) images named "a1.jpg", "a2.jpg", "a3.jpg", "a4.jpg", "a5.jpg", and "a6.jpg" repectively, in the same directory(folder) you saved the "load_img.htm" file if you realy want the above code to function acurately as expected.


Full Details