Search code examples
javascriptarrayssplice

Force first item to show onclick in an Array splice


I have managed to cobble this together with my limited js skills (I got the array splice working) and some help here (the prev-next nav).

The issue I'm having is the first item from the newly invoked array does not show immediately onclick. You have to first select the category/subject (animals, vehicles, etc.), and then click one of the nav arrows.

<head>
  <style>
    [onclick] {
      cursor: pointer;
    }
  </style>
</head>

<body>
  <div id="box">fruits</div>
  <button type="button" onclick="prev()">&#11207;</button>
  <button type="button" onclick="next()">&#11208;</button>

  <script>
    var fruits = ["apple", "banana", "orange"];
    var vehicles = ["car", "bus", "truck"];
    var body = ["eye", "ear", "nose"];
    var animals = ["lion", "tiger", "elephant"];

    var box = document.getElementById('box');
    var i = -1;

    function next() {
      i = i >= fruits.length - 1 ? 0 : i + 1;
      box.innerHTML = fruits[i];
    }

    function prev() {
      i = i > 0 ? i - 1 : fruits.length - 1;
      box.innerHTML = fruits[i];
    }
  </script>

  <script>
    function veh() {
      fruits = vehicles.slice(0);
    }

    function bod() {
      fruits = body.slice(0);
    }

    function ani() {
      fruits = animals.slice(0);
    }
  </script>
  <br/>
  <p onclick="veh()">vehicles</p>
  <p onclick="bod()">body</p>
  <p onclick="ani()">animals</p>
</body>


Solution

  • You can automatically use function next() to choose array

    function veh() {
      fruits = vehicles.slice(0);
      next()
    }
    

    <head>
      <style>
        [onclick] {
          cursor: pointer;
        }
      </style>
    </head>
    
    <body>
      <div id="box">fruits</div>
      <button type="button" onclick="prev()">&#11207;</button>
      <button type="button" onclick="next()">&#11208;</button>
    
      <script>
        var fruits = ["apple", "banana", "orange"];
        var vehicles = ["car", "bus", "truck"];
        var body = ["eye", "ear", "nose"];
        var animals = ["lion", "tiger", "elephant"];
    
        var box = document.getElementById('box');
        var i = -1;
    
        function next() {
          i = i >= fruits.length - 1 ? 0 : i + 1;
          box.innerHTML = fruits[i];
        }
    
        function prev() {
          i = i > 0 ? i - 1 : fruits.length - 1;
          box.innerHTML = fruits[i];
        }
      </script>
    
      <script>
        function veh() {
          fruits = vehicles.slice(0);
          next()
        }
    
        function bod() {
          fruits = body.slice(0);
          next()
        }
    
        function ani() {
          fruits = animals.slice(0);
          next()
        }
      </script>
      <br/>
      <p onclick="veh()">vehicles</p>
      <p onclick="bod()">body</p>
      <p onclick="ani()">animals</p>
    </body>