What is the best way to display the "next" and "previous" buttons for an item in an array?

I am currently attempting to use an array that contains 4 different maps. The initial element of the array should remain constant ("sticked") while the user can cycle through the rest of the elements by clicking the next button. Once the next button reaches the last item in the array, it should become disabled. The previous button should be initially disabled and when the next button is clicked, it should then become enabled. I am feeling quite lost at the moment, so any suggestions or advice would be greatly appreciated.

var i = 0;
var mapsArray = [
    "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d209569.44700750793!2d-56.380275318336025!3d-34.84309361411796!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x959f802b6753b221%3A0x3257eb39860f05a6!2sPalacio%20Salvo!5e0!3m2!1sen!2suy!4v1614269355326!5m2!1sen!2suy",
    "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d92110.09563909167!2d17.958933187703266!3d59.32686333113927!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x465f763119640bcb%3A0xa80d27d3679d7766!2sStockholm%2C%20Sweden!5e0!3m2!1sen!2suy!4v1614704350417!5m2!1sen!2suy",
    "https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d88989.45462143555!2d15.9390973!3d45.8128514!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4765d701f8ef1d1d%3A0x312b512f1e7f6df9!2sCathedral%20of%20Zagreb!5e0!3m2!1sen!2suy!4v1614704668458!5m2!1sen!2suy",
    "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d6709.917127499258!2d-78.51409209928569!3d0.3576385746900253!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8e2a5da2881494ab%3A0xae89047fc027c897!2sapuela%20imbabura%20intac!5e0!3m2!1en!2suy!4v1614704741586!5m2!1sen!2suy"
];
document.getElementById('myIframe').src = mapsArray[Math.floor(Math.random() * mapsArray.length)];

const prevBtn = document.querySelector(".prev");
const nextBtn = document.querySelector(".next");


function nextButton() {
    i = i + 1;
    i = i % mapsArray.length;
    return mapsArray[i];

}

function prevButton() {
    if (i === 0) {
        i = mapsArray.length;
    }
    i = i - 1;
    return mapsArray[i]
}
.maps {
     display: flex;
     justify-content: center;
     align-items: center;
 }

 #myIframe {
      width: 600px;
     height: 600px;
 }
<div class="maps">
  <iframe id='myIframe' class="maps-gallery active"></iframe>

</div>
<div class="btns">
  <button disabled onclick="nextButton()" class="btn prev">Prev</button>
  <button onclick="prevButton()" class="btn next">Next</button>

Answer №1

  1. Make sure to avoid naming your button and function the same, as this can cause errors in the console.

  2. To fix the issue, save your iframe in a variable and then use iFrame.src = mapsArray[i] inside both the back and next functions.

  3. Check the index numbers in the functions and disable the buttons accordingly based on whether it's the first, last, or middle number of the index array.

var i = 0;
var mapsArray = [
  "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d209569.44700750793!2d-56.380275318336025!3d-34.84309361411796!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x959f802b6753b221%3A0x3257eb39860f05a6!2sPalacio%20Salvo!5e0!3m2!1en!2suy!4v1614269355326!5m2!1sen!2suy",
  "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d92110.09563909167!2d17.958933187703266!3d59.32686333113927!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x465f763119640bcb%3A0xa80d27d3679d7766!2sStockholm%2C%20Sweden!5e0!3m2!1sen!2suy!4v1614704350417!5m2!1sen!2suy",
  "https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d88989.45462143555!2d15.9390973!3d45.8128514!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4765d701f8ef1d1d%3A0x312b512f1e7f6df9!2sCathedral%20of%20Zagreb!5e0!3m2!1en!2suy!4v1614704668458!5m2!1sen!2suy",
  "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d6709.917127499258!2d-78.51409209928569!3d0.3576385746900253!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8e2a5da2881494ab%3A0xae89047fc027c897!2sapuela%20imbabura%20intac!5e0!3m2!1en!2suy!4v1614704741586!5m2!1sen!2suy"
];

let iFrame = document.getElementById('myIframe')
iFrame.src = mapsArray[Math.floor(Math.random() * mapsArray.length)];

const prevB = document.querySelector(".prev");
const nextB = document.querySelector(".next");


function nextBtn() {
  console.clear()
  if (i >= 0 && i < 3) {
    iFrame.src = mapsArray[i]
    prevB.disabled = false
    console.log("next button array index set:" + i)
    i++
  } else {
    iFrame.src = mapsArray[i]
    nextB.disabled = true
    console.log("next button array index set:" + i)
    i++
  }
}

function prevBtn() {
  if (i === 0) {
    i = mapsArray.length;
  }
  i = i - 1;
  console.clear()
  console.log("prev array index:" + i)
  if (i <= 3 && i > 0) {
    iFrame.src = mapsArray[i]
    nextB.disabled = false
  } else {
    iFrame.src = mapsArray[i]
    prevB.disabled = true
  }


}
.maps {
  display: flex;
  justify-content: center;
  align-items: center;
}

#myIframe {
  width: 150px;
  height: 150px;
}
<div class="maps">
  <iframe id='myIframe' class="maps-gallery active"></iframe>

</div>
<div class="btns">
  <button disabled onclick="prevBtn()" class="btn prev">Prev</button>
  <button onclick="nextBtn()" class="btn next">Next</button>
</div>

Answer №2

Here is the solution:

var mapsArray = [
  "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d209569.44700750793!2d-56.380275318336025!3d-34.84309361411796!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x959f802b6753b221%3A0x3257eb39860f05a6!2sPalacio%20Salvo!5e0!3m2!1en!2suy!4v1614269355326!5m2!1sen!2suy",
  "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d92110.09563909167!2d17.958933187703266!3d59.32686333113927!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x465f763119640bcb%3A0xa80d27d3679d7766!2sStockholm%2C%20Sweden!5e0!3m2!1sen!2suy!4v1614704350417!5m2!1sen!2suy",
  "https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d88989.45462143555!2d15.9390973!3d45.8128514!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4765d701f8ef1d1d%3A0x312b512f1e7f6df9!2sCathedral%20of%20Zagreb!5e0!3m2!1en!2suy!4v1614704668458!5m2!1sen!2suy",
  "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d6709.917127499258!2d-78.51409209928569!3d0.3576385746900253!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8e2a5da2881494ab%3A0xae89047fc027c897!2sapuela%20imbabura%20intac!5e0!3m2!1en!2suy!4v1614704741586!5m2!1sen!2suy"
];
var i = Math.floor(Math.random() * mapsArray.length);
var iFrameElement = document.getElementById('myiFrame')
iFrameElement .src = mapsArray[i];

function nextBtn() {
  if (i === mapsArray.length) i = 0;
  else i += 1;
  iFrameElement.src = mapsArray[i];
}

function prevBtn() {
  if (i === 0) i = mapsArray.length;
  else i -= 1;
  iFrameElement.src = mapsArray[i];
}
.maps {
  display: flex;
  justify-content: center;
  align-items: center;
}

#myiFrame {
  width: 600px;
  height: 600px;
}
<div class="maps">
  <iframe id="myiFrame"></iframe>
</div>

<div class="btns">
  <button onclick="nextBtn()">Prev</button>
  <button onclick="prevBtn()">Next</button>
</div>

Answer №3

Here is a straightforward method:

var mapsArray = [
  "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d209569.44700750793!2d-56.380275318336025!3d-34.84309361411796!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x959f802b6753b221%3A0x3257eb39860f05a6!2sPalacio%20Salvo!5e0!3m2!1sen!2suy!4v1614269355326!5m2!1sen!2suy",
  "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d92110.09563909167!2d17.958933187703266!3d59.32686333113927!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x465f763119640bcb%3A0xa80d27d3679d7766!2sStockholm%2C%20Sweden!5e0!3m2!1sen!2suy!4v1614704350417!5m2!1sen!2suy",
  "https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d88989.45462143555!2d15.9390973!3d45.8128514!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4765d701f8ef1d1d%3A0x312b512f1e7f6df9!2sCathedral%20of%20Zagreb!5e0!3m2!1sen!2suy!4v1614704668458!5m2!1sen!2suy",
  "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d6709.917127499258!2d-78.51409209928569!3d0.3576385746900253!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8e2a5da2881494ab%3A0xae89047fc027c897!2sapuela%20imbabura%20intac!5e0!3m2!1sen!2suy!4v1614704741586!5m2!1sen!2suy"
];
var index = 0;
const _prevBtn = document.querySelector(".prev");
const _nextBtn = document.querySelector(".next");

update();

function update() {
  document.getElementById('myIframe').src = mapsArray[index];
  btnDisableCheck();
}

function nextBtn() {
  if (index < mapsArray.length - 1) {
    index++;
    _prevBtn.disabled = false;
    update();
  }
}

function prevBtn() {
  if (index > 0) {
    index--;
    _nextBtn.disabled = false;
    update();
  }
}

function btnDisableCheck() {
  if (index == 0)
    _prevBtn.disabled = true;
  if (index == mapsArray.length - 1)
    _nextBtn.disabled = true;
}
<iframe id='myIframe' class="maps-gallery active"></iframe>
<button onclick="prevBtn()" class="btn prev">Prev</button>
<button onclick="nextBtn()" class="btn next">Next</button>

Answer №4

Here is the solution you requested, with a few adjustments made:

var  locationsArray = [
    "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d209569.44700750793!2d-56.380275318336025!3d-34.84309361411796!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x959f802b6753b221%3A0x3257eb39860f05a6!2sPalacio%20Salvo!5e0!3m2!1en!2suy!4v1614269355326!5m2!1en!2suy",
    "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d92110.09563909167!2d17.958933187703266!3d59.32686333113927!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x465f763119640bcb%3A0xa80d27d3679d7766!2sStockholm%2C%20Sweden!5e0!3m2!1en!2suy!4v1614704350417!5m2!1en!2suy",
    "https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d88989.45462143555!2d15.9390973!3d45.8128514!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4765d701f8ef1d1d%3A0x312b512f1e7f6df9!2sCathedral%20of%20Zagreb!5e0!3m2!1en!2suy!4v1614704668458!5m2!1en!2suy",
    "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d6709.917127499258!2d-78.51409209928569!3d0.3576385746900253!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8e2a5da2881494ab%3A0xae89047fc027c897!2sapuela%20imbabura%20intac!5e0!3m2!1en!2suy!4v1614704741586!5m2!1en!2suy"
];
var myFrame = document.getElementById('myFrame');
var previousButton = document.getElementById('prevBtn');
var nextButton = document.getElementById('nextBtn');
var position = Math.floor(Math.random() * locationsArray.length);

function updateLocation() {
    myFrame.src = locationsArray[position];
    if ( position == locationsArray.length - 1 ) {
        previousButton.disabled = false;
        nextButton.disabled = true;
    }
    else if ( position == 0 ) {
        previousButton.disabled = true;
        nextButton.disabled = false;
    }
    else {
        previousButton.disabled = false;
        nextButton.disabled = false;
    }
}

function goToNext() {
    if ( position < locationsArray.length - 1 ) {
        position++;
    }
    updateLocation();
}

function goToPrevious() {
    if (position > 0) {
        position--;  
    }
    updateLocation();
}

updateLocation();
.locations{
  display: flex;
  justify-content: center;
  align-items: center;
}

#myIframe {
  width: 600px;
  height: 600px;
}
<div class ="locations">
    <iframe id='myFrame' class="locations-display active"></iframe>
</div> 
<div class="buttons">
    <button id="prevBtn" onclick="goToPrevious()" class="button previous">Previous</button>
    <button id="nextBtn" onclick="goToNext()" class= "button next" >Next</button>
</div> 

Answer №5

Here is a simple solution to address your issue. The concise approach may not appeal to everyone, but it demonstrates the minimal amount of code required to replicate the logic.

The fundamental aspect of randomly sequencing array elements involves shuffling the array using the Fisher-Yates algorithm. Following that, I iterate through the shuffled array and enable/disable buttons as needed.

function shuffle(a,n){ // in-place array shuffling (Fisher-Yates)
 let m=a.length;
 n=n||m-1;
 for(let i=0,j;i<n;i++){
  j=Math.floor(Math.random()*(m-i)+i);
  if (j-i) [ a[i],a[j] ] = [ a[j],a[i] ]; // swap 2 array elements
 }; return a
}
const mapsArray = shuffle([
  "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d209569.44700750793!2d-56.380275318336025!3d-34.84309361411796!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x959f802b6753b221%3A0x3257eb39860f05a6!2sPalacio%20Salvo!5e0!3m2!1sen!2suy!4v1614269355326!5m2!1sen!2suy",
  "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d92110.09563909167!2d17.958933187703266!3d59.32686333113927!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x465f763119640bcb%3A0xa80d27d3679d7766!2sStockholm%2C%20Sweden!5e0!3m2!1sen!2suy!4v1614704350417!5m2!1sen!2suy",
  "https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d88989.45462143555!2d15.9390973!3d45.8128514!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4765d701f8ef1d1d%3A0x312b512f1e7f6df9!2sCathedral%20of%20Zagreb!5e0!3m2!1sen!2suy!4v1614704668458!5m2!1sen!2suy",
  "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d6709.917127499258!2d-78.51409209928569!3d0.3576385746900253!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8e2a5da2881 494ab%3A0xae89047fc027c897!2sapuela%20imbabura%20intac!5e0!3m2!1en!2suy!4v1614704741586!5m2!1en!2suy"]);
  btns=document.querySelectorAll("button"), trgt=document.getElementById('myIframe'); 
trgt.src=mapsArray[0];
(i=>{
  let n=mapsArray.length;
  btns.forEach((b,k)=>b.onclick=()=>{
      trgt.src=mapsArray[i=i+2*k-1];
      btns[0].disabled=!i; btns[1].disabled=(i+1===n);
  })  
})(1); btns[0].click();
.maps {
  display: flex;
  justify-content: center;
  align-items: center;
}

#myIframe {
  width: 600px;
  height: 600px;
}
<iframe id='myIframe' class="maps-gallery active"></iframe><br>
<button>Prev</button>
<button>Next</button>

The primary function is encapsulated within an Immediately Invoked Function Expression (IIFE), which maintains the current position index i and initializes it to 0. The only public components are the shuffle() function and the mapsArray itself. To handle navigation, I leverage the use of k within the .forEach() loop to determine whether 'next' (=1) or 'previous' (=0) was clicked, allowing for dynamic adjustment of the increment value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arrange blocks within bootstrap columns using grid css

I have a layout with two columns, each containing two blocks Currently, the mobile order is: 1 2 3 4 But I want it to be: 3 1 2 4 I attempted to use CSS grid but I am unsure how to move block 3 out of column 2. Here's the code snippet: body { ...

Is there a way to load and play different sounds on multiple audio players based on the length of an array?

I am attempting to load various sounds (.mp3 audio) on separate audio players that are displayed on a single HTML page. The number of players displayed on the screen is determined by the length of the array. In this specific example, I have 3 elements in t ...

Execute a VueJS API call every 20 minutes

I am retrieving data from an API endpoint to display information about coin names. I would like this information to update every 20 minutes, but for testing purposes, I have set it to refresh every 500 milliseconds. However, my current approach of fetching ...

Transforming an Angular 11 HTML template into Angular code

After attempting to transfer the Porto Admin HTML template to Angular, I encountered some issues. When including the CSS and JS dependencies in the project, everything worked fine with all the HTML code in index.html. However, when I moved the code to app. ...

Automating the compression of JavaScript with YUI Compressor, excluding specific files

I came across a helpful solution on this Stack Overflow thread: How can I automate the compression of JavaScript files using YUI Compressor? But here's my dilemma: I have a bunch of jQuery files in my ~/Scripts directory that are already compressed ...

What is the best method to redirect users who are not logged in from every URL when using PassportJs?

I am currently developing a web application using NodeJS, and I have integrated PassportJS with passport-local-mongoose for authentication. Below is the code snippet I've created for the root route to verify if the user is logged in: app.get('/ ...

Using AngularJS, deleting items by their $index with ng-repeat

I'm currently working with two directives: a query builder and a query row. The query builder directive utilizes ng repeat to display query rows from an array. While the add button functions properly, I am looking to add a delete button as well. Howev ...

What is the best way to transmit a modified variable from a client to a server using the fetch API?

I'm facing a challenge in sending a modified variable from the client to the server and utilizing it in main.ejs. Here's my current code: <script> document.getElementById("char2btn").addEventListener("click", change) fun ...

Having trouble getting your AngularJS code to work?

Recently, I decided to experiment with AngularJS and started working on a new project. Below is the HTML code I wrote: <div ng-app ng-controller="nameController"> <input type="text" value="Jack" ng-model="fname" /> <input type="tex ...

Extracting specific data from a JSON subnode within an HTML document

I have been attempting to retrieve product data (name, price, url), along with information on available sizes and colors, from a website that is formatted in JSON (https://www.bergzeit.de/marken/salewa/). However, I am struggling to locate the 'elemen ...

The array is present both before and after the res.json() call, however it appears empty in the response

When using Express to send a json response with res.json(), I am experiencing an issue where the value of records in the object sent via res.json() is empty. My code snippet looks like this: stats.activities(params).then(res => { processActivities ...

Performing numerous asynchronous MongoDB queries in Node.js

Is there a better way to write multiple queries in succession? For example: Space.findOne({ _id: id }, function(err, space) { User.findOne({ user_id: userid }, function(err, user) { res.json({ space: space, user: user}); }); }); It can g ...

Creating a row in your HTML frontend with automated three-column cards

Hello everyone, I am currently new to Django and also learning HTML simultaneously. I am working on a small project in Django, but encountering a problem with the frontend part, specifically related to HTML elements. As you can see in the image attache ...

The route param is throwing a "Cannot read property 'name' of undefined" error, indicating that the property

Currently, I am enrolled in an ExpressJS course on TUTS+ From the video tutorial, I have implemented the following code snippet (excerpt from video): var express = require('express'), app = express(); app.get('/name/:name', funct ...

Is it possible to disregard text formatting in Python when using Selenium?

I am experiencing an issue when trying to compare a name from my name string to a name in a webelement. For instance: Name format in my namestring (scraped from a website): Mcburnie Name in webelement: McBurnie The Xpath matching fails because the webe ...

The scale configuration for scale: x is not valid for creating a time scale chart using chart.js

I am currently utilizing VueJS and attempting to integrate a time scale chart using Chart.js. However, I encountered the following error: Invalid scale configuration for scale: x Below is my configuration : First, I have a component named Chart.vue with ...

Tips for transmitting an array of Objects to AngularJS

Summary I'm curious about how I can successfully send the following array of objects from NodeJS to an AngularJS app. var players = [ Footer: { username: 'Footer', hp: 200, exp: 1 }, Barter: { username: 'Barter', hp: 200, e ...

Click to activate the Selectfield option

There are 3 links that populate the select field with various options. When the text label is active and someone clicks on the link selectlist1 or another, it should activate the select label. How can this be achieved? <!doctype html> <html> ...

Animating a jQuery Knob as you scroll from 0 to a set value

I am new to jQuery and currently working on jQuery Knob. Everything is functioning properly, but I have encountered an issue. When scrolling to the section with the knobs, I would like them to animate from 0 to a specific value. Is there a way to achieve ...

Organize information by time intervals using JavaScript

I am currently facing an issue where I need to dynamically sort data from the server based on different fields. While sorting is working flawlessly for all fields, I am encountering a problem with the time slot field. The challenge lies in sorting the data ...