Unimpressed Lemur Unimpressed Lemur - 5 months ago 8
Javascript Question

'for' loop used for array not working in this simple script

See the following code:

function overall() {
var message = ["dog", "cat", "bear", "penguin", "tiger", "eagle", "John Doe"];
function forward() {
var A = document.getElementById('text');
for (var i = 0; i < message.length+1; i++) {
if (A.innerHTML===message[i]) {
A.innerHTML = message[i+1];
};
};
};
function backward() {
var A = document.getElementById('text');
for (var i = 0; i < message.length+1; i++) {
if (A.innerHTML===message[i]) {
A.innerHTML = message[i-1];
};
};
};
};


In the above JS script, my intention is when the forward() function is called, animal in the '.innerHTML' should change to an animal after that one in the array called 'message' using the for loop.
Similarly, when the backward() function is called, animal in the '.innerHTML' should change to an animal before that one in the said array.

I verified my script and there are, supposedly, no syntactical errors. That means there is an error in my logic. Please help me out. Thanks!

The HTML:

<html>
<head></head>
<body>
<p id="text">dog</p>
<div id='right' onclick="forward()"></div>
<div id="left" onclick="backward()"></div>
</body>
</html>

Answer

This help you :

<html>
<head>
    <style>
    </style>
</head>
    <body>
        <p id="text">cat</p>
        <button id="btn1" onclick="forward()">Next</button>
        <button id="btn2" onclick="backward()">previous</button>
        <script>
                    var message = ["dog", "cat", "bear", "penguin", "tiger", "eagle", "John Doe"];
                    function forward() {
                        var A = document.getElementById('text');
                        for (var i = 0; i < message.length-1; i++) {
                            if (A.innerHTML === message[i]) {
                                A.innerHTML = message[i+1];
                                break;
                            }
                        }
                    }
                    function backward() {
                        var A = document.getElementById('text');
                        for (var i = message.length-1; i > 0; i--) {
                            if (A.innerHTML===message[i]) {
                                A.innerHTML = message[i-1];
                                break;
                            }
                        }
                    }
        </script>
    </body>
</html>