How can I retrieve the matching array element from another array?

Apologies for the vague title, I'm struggling to convey my issue clearly. I've tried looking through similar posts but couldn't find a solution that fits my needs.

Here's what I'm attempting to achieve:

I want to create an array containing elements from the DOM like this:

var boxes = ["box1", "box2", "box3"]

Additionally, I need an array of popups with display:none

var popups = ["pop1", "pop2", "pop3"]

The goal is to click on boxes[i] and have it open popups[i].

My question is how do I capture the [i] event so I can correctly link it to open the corresponding popup?

Although I haven't included code here, you can refer to this template as guidance:

var boxes = document.getElementsByClassName("box");
var popupss = document.getElementsByClassName("pop");
.wrapper {
  display: flex;
  justify-content:space-between;
}

.box {
  cursor:pointer;
  display:flex;
  justify-content:center;
  align-items:center;
  background-color: #FC543A;
  padding: 50px;
  border-radius: 3px;
}

.wrapper2 {
  display:flex;
  justify-content:center;
  background-color: rgba(0,0,0,0.4);
  position:fixed;
  height:100%;
  width:100%;
  z-index:2;
  overflow:auto;
}

.pop {
  margin-top:6em;
  background-color:white;
  height: 50px;
  width: 80%;
  display:none;
  justify-content:center;
  align-items:center;
}

.hide {
  display:none;
}

.show {
  display:flex;
}
<div class="wrapper">
  <div id="box1" class="box">Box1</div>
  <div id="box2" class="box">Box2</div>
  <div id="box3" class="box">Box3</div>
</div>

<div class="wrapper2">
  <div class="pop" id="pop1">
  Pop1!
  </div>
  
  <div class="pop" id="pop2">
  Pop2!
  </div>
  
  <div class="pop" id="pop3">
  Pop3!
  </div>
</div>

Thank you!

Answer №1

Here is a solution with detailed comments. Click on the boxes below to see the pop-ups.

Javascript functions used:

//select all divs with class box and iterate them
Array.prototype.forEach.call(document.querySelectorAll("div.box"), function(element, index) {
  //we use Array.prototype.map and use call to pass the node list into the map function to iterate

  //assign click handlers
  //when an element is clicked it will fire the function boxHandler. We use bind to pass the index of the element to the function.
  element.addEventListener("click", boxHandler.bind(element, index), true);

  //hide all pops
  document.querySelectorAll("div.pop")[index].classList.add("hide");
});

function boxHandler(index) {
  //select the div based upon the index. 
  var pop = document.querySelectorAll("div.pop")[index];
  if (pop.getAttribute("data-clicked") != 1) {
    //add show to class using classlist.add
    pop.classList.add("show");
    pop.classList.remove("hide");
    pop.setAttribute("data-clicked", 1);
  } else {
    pop.classList.remove("show");
    pop.classList.add("hide");
    pop.setAttribute("data-clicked", 0);
  }

}
.wrapper {
  display: flex;
  justify-content: space-between;
}

.box {
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #FC543A;
  padding: 50px;
  border-radius: 3px;
}

.wrapper2 {
  display: flex;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.4);
  position: fixed;
  height: 100%;
  width: 100%;
  z-index: 2;
  overflow: auto;
}

.pop {
  margin-top: 6em;
  background-color: white;
  height: 50px;
  width: 80%;
  display: none;
  justify-content: center;
  align-items: center;
}

.hide {
  display: none;
}

.show {
  display: flex;
}
<div class="wrapper">
  <div id="box1" class="box">Box1</div>
  <div id="box2" class="box">Box2</div>
  <div id="box3" class="box">Box3</div>
</div>

<div class="wrapper2">
  <div class="pop" id="pop1">
    Pop1!
  </div>

  <div class="pop" id="pop2">
    Pop2!
  </div>

  <div class="pop" id="pop3">
    Pop3!
  </div>
</div>

Answer №2

Your coding strategy could use some improvement. Instead of duplicating code, try to pause and reconsider your approach. Rather than creating separate HTML pop sections, it's more efficient to have a single HTML placeholder for the pop message and store the possible values in a JavaScript array. This not only simplifies the HTML structure but also eliminates the need for a .hide CSS class.

Simply assign each box a click event function that dynamically sets the corresponding pop message from the array into the pop placeholder.

// Store possible pop messages:
var popMessages = ["Pop1!", "Pop2!", "Pop3!"];

// Reference the pop placeholder
var pop = document.getElementById("pop");

// Use .querySelectorAll() instead of .getElementsByClassName for better performance
var boxes = Array.prototype.slice.call(document.querySelectorAll(".box"));

// Loop through the boxes
boxes.forEach(function(box, index){
  // Set click event handling function for each box
  box.addEventListener("click", function(){
    // Assign the pop message based on the index of the clicked box
    pop.textContent = popMessages[index];
  });
});
.wrapper {
  display: flex;
  justify-content:space-between;
}

.box {
  cursor:pointer;
  display:flex;
  justify-content:center;
  align-items:center;
  background-color: #FC543A;
  padding: 50px;
  border-radius: 3px;
}

.wrapper2 {
  display:flex;
  justify-content:center;
  background-color: rgba(0,0,0,0.4);
  position:fixed;
  height:100%;
  width:100%;
  z-index:2;
  overflow:auto;
}

.show {
  display:flex;
}
<div class="wrapper">
  <div id="box1" class="box">Box1</div>
  <div id="box2" class="box">Box2</div>
  <div id="box3" class="box">Box3</div>
</div>

<div class="wrapper2">
  <div class="pop" id="pop"></div>
</div>

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

What is the best way to create a reusable component for Cards and implement the new makeStyles feature in material-ui?

Within the depths of my demo.js file, I desire to utilize the Card component with its nested CardHeader and fill in some text within the CardContent. Furthermore, I aim to make the CardComponent easily reusable across multiple files. Any suggestions on how ...

Which javascript array libraries, utilities, or extensions are considered the top choices?

Dojo's array utilities have been useful, but I find that they lack certain features that I need. Are there any comprehensive and well-written JavaScript array utility libraries or extensions available? I'm looking for something that offers a wid ...

Mesh object circling in the opposite direction of the displayed image

Working on replicating a Flash website using Three.JS and facing difficulty in achieving desired functionality. The goal is to create button images that orbit around the center of the screen, stop when hovered over by the mouse, and open a different locat ...

Can individual items be removed one by one from a newly created int[] array?

int *ptr_Array; ptr_Array = new int[5]; Is there a way to remove the last element in this array? I am able to add elements one by one using PUSH. Alternatively, I can delete the entire array. delete []ptr_Array; ptr_Array = NULL; I have not been success ...

Using Vue3 and Vuex4: How to efficiently render only a subset of items from an array with v-for

Hello, I'm a first-time user and beginner developer seeking some assistance. I am in the process of creating a basic web application that retrieves an HTTP JSON response from an API and displays a more visually appealing list of results. However, I&ap ...

Sending JSON data using Ajax with circular reference

The JSON structure I am working with is as follows: "node": { "id": "812de6d0-a754-11e7-a7d4-47a3233fb668", "name": "123", "type": "node", "children": [ { "id": "d517b899-d211-4896-8eeb-466268ddf2e3", "name" ...

Tips for automatically updating a table on 'wix' when adding data to a dataset through a submit button

Is there a way to automatically update the table without needing to refresh the browser every time we press the submit button? ...

React Native App experiences immediate crashes when launched on TestFlight

I've encountered a frustrating issue with my application that keeps crashing when loaded into Testflight. To troubleshoot, I decided to start from scratch and created a basic expo react native application to pinpoint the source of the problem. After ...

I attempted to create a callable function for creating a user, but I encountered an error when running it and I am unable to determine the cause

I'm in the process of creating a user management page and have set up a callable function on Firebase to handle the creation of new users. The HTML function I've designed is supposed to update existing users or create new ones. However, when test ...

Tips on bringing data from a php file into a javascript variable

I'm faced with a challenge where I need to extract data from a MySQL database using a PHP file and then store that data in a JavaScript array for plotting purposes with jQuery's flot library. Has anyone encountered a similar situation and found a ...

Guide on implementing datatables.js in a Vue.js2 project

I am looking to implement a dynamic Datatable in my Laravel and Vue.js project. I have integrated the datatables.js library for displaying my data. However, when I fetch data from an API call which returns an array, I am facing issues with populating the d ...

Suggestion: optimal placement for HTML table data - JavaScript or HTML?

Should I change my Python code to generate a JavaScript file instead of a webpage with a table? I am unsure of the advantages and disadvantages of this approach. Any insights or experiences to share? Are there alternative solutions that I should consider? ...

Is there a way to send both a JSON object and a zipped folder in one request from a single endpoint in Spring Boot?

I am currently working on a project that requires generating multiple CSV reports, their corresponding PDF versions, and zipping them all together with a JSON object containing summaries of the exported files. The user should be able to view these summarie ...

Is there a method to asynchronously set items in local storage using JavaScript?

Is there a way to asynchronously set a value in local storage while using an ionic app to validate token-based authentication? Currently, it is taking some time to store the token in local storage before moving on to the next state. window.localStorage. ...

typescript set x and y values to specific coordinates

Trying to map obstacles using a single object. Originally scattered randomly across the map, now I want to hard code X & Y coordinates with an array of numbers. However, TypeScript is only using the last value of the loop for the X coordinate. How can I a ...

Looking for assistance grasping the concept of using a for loop in MongoDB's aggregate method

This code snippet is designed to maintain the order of an array (var list) when utilizing mongoDb's $in clause effectively. Although, I must admit that the logic behind it is not entirely clear to me. I can see that it's iterating in reverse to ...

Display: Show view once forEach loop finishes execution

I'm facing an issue with my update query execution within a loop. Is there a way to trigger the rendering of a view once the forEach loop completes all its iterations? Here's the snippet of code: conn.query(`SELECT Id, ${sfColumn} from Lead`, ...

Developing a Cloud Function for Stripe that is taking forever to finalize writing data to Firestore

Currently, I am facing an issue with my Google Cloud function (provided below) that handles webhooks from Stripe payments and stores some data in Firestore. The problem is that it seems to hang for approximately 3 minutes before completing. const Stripe = ...

Unable to alphabetically arrange buttons automatically

I am encountering a challenge with automatically sorting buttons alphabetically on my webpage. I am unable to determine the method for sorting these buttons using jquery or javascript, but my goal is to have them sorted automatically when the page loads. I ...

What are the reasons for issues arising in the findConsecutiveOnes Java code when the input size grows significantly?

I was tasked with determining the longest consecutive sequence of ones in an array. For example, in the array [1,0,1,1], the expected result would be 2. Initially, I developed a code that performed well for small arrays. public int findMaxConsecutiveOne ...