Creating a JavaScript gallery: change the actual image

233 Views Asked by At

I have tried the various solutions on the site, but I suspect I am doing something wrong with implementing the actual image in the document, or anything. Thanks in advance for the help!

Here is my current code:

<html>
<body>

<link type="text/css" rel="stylesheet" href="Stylesheet.css"/>


<img id="teemoimage" src="exampleurl">


<script>
    var leagueofteemo=new Array()
    var counter = 1
    leagueofteemo[1]="exampleurl"
    leageuofteemo[2]="exampleurl"

    function back()
    {
    if (counter = 1)
        {
    counter = leagueofteemo.length;
    }
        else
        {
    counter--;
    }
        document.getElementById("teemoimage").src =leagueofteemo[counter]
    }

    function foward()
    {
        if (counter = leageofteemo.length)
        {
    counter = 1;
    }
        else
        {
    counter++;
    }
        document.getElementById("teemoimage").src = leageuofteemo[counter];
}
</script>

<form>
    <input type="button" onclick="back()" value="Back">
    <input type="button" onclick="foward()" value="Foward">
</form>
1

There are 1 best solutions below

2
On

There's a few things wrong with your code.

  • your equality operators are incorrect,
  • js arrays are 0 based. So rather start your array at 0.
  • leagueofteemo variable is spelled incorrectly in some instances

I suggest you use some sort of tool to help you debug your JavaScript e.g. Firebug. Alternatively you can use the developer tools that comes standard with most browsers these days.

I've revised your sample to be syntactically and semantically correct but haven't tested it:

var leagueofteemo = new Array();
var counter = 0;
leagueofteemo[0] = "exampleurl";
leageuofteemo[1] = "exampleurl";

function back() {
    if (counter === 0) {
        counter = leagueofteemo.length;
    }
    else {
        counter--;
    }

    document.getElementById("teemoimage").src = leagueofteemo[counter];
}

function foward() {
    if (counter === leagueofteemo.length-1) {
        counter = 0;
    }
    else {
        counter++;
    }

    document.getElementById("teemoimage").src = leagueofteemo[counter];
}