'How do I get the Rolls Royce?

By scrolling forwards or backwards, I want to retrieve relevant information from the array. Why is'nt the value of "page" valid in document.getElementById("car").innerHTML = (cars[page][0]);

<!DOCTYPE html>
<html lang='sv-se'>  
<head>
<title>Page Scroll</title>
<meta charset='utf-8'>
<script>
    const cars = [ [ 'Ford' ],[ 'Rolls Royce' ],[ 'Bentley' ],[ 'Volvo' ],];
</script>
<script>var page = 0;let length = cars.length;</script>
</head>

<body style='text-align:center;'>
<h1 id='page'>0</h1>
<h2 id='car'>Car</h2>
<button type='button' onclick='prevPage()'> PREV </button>
Scroll with the arrows
<button type='button' onclick='newPage()'> NEXT </button>

<p>The length of the data file: <a id='len'>0</a></p>

<script>
function newPage() {
    if (page > length - 2) {
      page = 0;
    } else {
      page += 1;
    }
    document.getElementById('page').innerHTML = page;
};
function prevPage() {
    if (page < 1) {
    page = length - 1;
    } else {
      page -= 1;
    }
    document.getElementById('page').innerHTML = page;
};
</script>

<script>
document.getElementById('car').innerHTML = (cars[page][0]);
document.getElementById('len').innerHTML = length; 
</script>
</body></html>


Solution 1:[1]

document.getElementById('car').innerHTML = (cars[page][0]); only ever runs once, at the start of the page loading. Add it to your code in nextPage and prevPage

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TKoL