Show the components of an associative array with a click of a button

I have a total of four div elements and array elements. My goal is to link these two components together effectively.

Specifically, when a user clicks on the first div element with the class .news, I want to display the values of the first element in the array within the div #selectedNews.

You can view my code here

The main issue I am facing is understanding how to establish a connection between the div elements and the array elements.

Here is the code snippet again:

var newsListData = [
  {
    "group" : "science",
    "title" : "Text 1",
    "image" : "images/news1.jpg",
    "content" : "Text text text"
},
{
    "group" : "science",
    "title" : "Text 2",
    "image" : "images/news2.jpg",
    "content" : "Text text text"
},
{
    "group" : "science",
    "title" : 'Text 3',
    "image" : "images/news3.jpg",
    "content" : "Text text text"
},
{
    "group" : "economics",
    "title" : 'Text 4',
    "image" : "images/news4.jpg",
    "content" : "Text text text"
}]

var selected;
function elem() {
  selected.innerHTML = "";
  for (var i = 0; i < this.children.length; i++) {
    selected.appendChild(this.children[i].cloneNode(true));
  }
}

document.addEventListener("DOMContentLoaded", function() {
  var selectedNews = newsListData​ /* stuck HERE */
  for (var i = 0; i < selectedNews.length; i++) {
    selectedNews[i].addEventListener("click", elem);
  }
  selected = document.getElementById("selectedNews")
});
#selectedNews {
  border : 1px solid gray;
  margin : 10px;
  padding : 5px;
}

.news {
  background-color: green;
  border: 2px solid black;
  padding: 4px;
  margin-top: 2px;
  text-align: center;
}
<div id="newsList">
<input type="text" placeholder="filter..." id="filter"/>
<div class="list"> 
<div id="0-news" class="news">One</div>
    <div id="1-news" class="news">Two</div>
    <div id="2-news" class="news">Three</div>
    <div id="3-news" class="news">Last one</div>
    

<article id="selectedNews">
<h1>Titre</h1>
<figure>
<img src="" alt="titre"/>
</figure>
<div id="content">
bla bla
</div>
</article>    

Answer №1

If you want to display a specific item from an array, you will need to know the index of that item. One way to achieve this is by adding an event listener to elements with the class .news, as shown in the example below:

<div id="0-news" class="news" onclick="showItem(0)">Item One</div>

Here is how you can implement this in your JavaScript code:

window.showItem = function(index) {
    var selectedData = dataArray[index]; // retrieve the data at the specified index
    // further logic to display the selected data goes here
}

You can view a demo of this implementation here.

Additionally, you can dynamically create buttons based on your data using a loop:

var newsContainer = document.getElementById("newsContainer");
var button;

for (var i = 0; i < dataArray.length; i++) {
    button = document.createElement("button"); // create a button element

    button.setAttribute("id", i + "-news"); // set the id attribute

    button.onclick = showItem(i); // attach event listener to display respective data

    newsContainer.appendChild(button); // add the button to the container
}

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

Integrating force refresh functionality into a React application

I currently have a React application running on an apache/PHP server. The React app is set to load on the home path by configuring PHP to load index.html at the / route, which then loads the React app. index.html // .... <div id="react-hook"></ ...

Conceal the footer using CSS while the slide is in focus

Trying to figure out a way to hide the footer when a specific container is active: For example, how can I hide the footer when the second and third items are selected as active? <div class="owl-stage"> <div class="owl-item"></div> & ...

Using conditional CSS in React/Next.js

While using Next.js, I have implemented conditional rendering on components successfully. However, I am facing an issue where the CSS styles differ between different components. Code 1: import React from "react"; import Profile from "../../ ...

The webpack-dev-server is displaying an error message, stating "Unable to access /"

I've been troubleshooting my webpack-dev-server setup, but I keep encountering the "Cannot Get /" error in the browser. Despite looking through similar questions with the same issue, none of the solutions have worked for me so far. So, here's hop ...

Guide to creating a JavaScript function that receives inputs from several other functions

I need help adding a new function to this code that will show the difference between the values calculated by the existing functions, but I'm not sure how to go about implementing it. <!DOCTYPE html> <html lang="en"> <head> ...

Issue with SVG on tainted canvas causes IE security error when using toDataURL

In my Angular JS directive, I have implemented a feature to export SVGs to PNG. While this functionality works seamlessly in most browsers, it encounters a security error in IE. Despite my numerous attempts to troubleshoot the issue, I have been unable to ...

Clicking on the Form.Label in React-Bootstrap triggers the opening of the file explorer

Hey there, I hope everyone is having a great day. In my application, there are various forms that appear as popup modals. I have been using React-Bootstrap for most of the components in my app. However, I recently noticed that whenever I click on a <Fo ...

What could be causing the React state not to update properly?

Having an issue with my Alice-Carousel in react. I'm fetching items from an API and updating the array for the carousel, but the value of items keeps coming back as undefined. Using CryptoState context to avoid prop drilling. import React from 'r ...

Complicated "as-label" for understanding expressions in Angular

Is it possible to set a complex label in a comprehension expression in Angular? I've searched everywhere for a solution, but I can't seem to find one. The workaround I found involves pre-populating the 'as' label attribute with the des ...

php-ews: Fatal error: Unhandled SoapFault exception: [Client] The class 'EWS_Exception' is not found

Issue with Exchange Server Code For the past year, my code has been running smoothly without any problems. However, yesterday, I encountered an error message that disrupted its functionality. The code is designed to retrieve the number of unread emails in ...

The onclick event for a Bootstrap .btn-group checkbox functions correctly in JSFiddle, but encounters issues when tested

The toggle button group in the form below utilizes Bootstrap and checkboxes. I am looking to track click events on the checkbox inputs. <html> <head> <title>Example: Bootstrap toggle button group</title> <meta charset="UTF-8 ...

Issues with Angular $watch causing mismatches in bindings更新(binding)

I am attempting to set default values for certain model properties by using $watches. I cannot utilize the typical two-way binding because I want the model properties to start off as empty. Although the $watches are successfully setting the properties, the ...

Experiencing a "non-serializable value found in the state" error specifically while utilizing redux toolkit, but this issue does not occur with traditional redux implementations

While transitioning my app to utilize Redux Toolkit, I encountered an error after switching over from createStore to configureStore: A non-serializable value was found in the state at path: `varietals.red.0`. Value:, Varietal { "color": "red", "id": " ...

What is the best method to extract information from a string using PHP?

I am working with an array that includes the following days: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday. My goal is to display each day separately and add a checkbox next to it. Any assistance would be greatly appreciated. Thank you. ...

What could be the reason why the date in my code is not showing up in the input field in the format dd-M-yy after it has been

Here is the code snippet I have been working on. To start, run the index.php file. This will display a dropdown list where you can select either value 1 or 2. If you choose 2, the selected value along with the "date" field from display-date.php will be sh ...

Correct placement of elements using absolute positioning and optimized scroll functionality

I am currently working on implementing tooltips for items within a scrollable list. My goals for the tooltips are as follows: Ensure they are visible outside and not restricted by the scroll area Appear immediately after the corresponding item Be detach ...

I made some adjustments to the program, but I'm having trouble identifying the issue

Here's a simple form I'm using to input and send the category name: <form action="insertexp.php" method="post"> Category Name: <input type="text" name="name"><br> <input type="submit"> </form> This is my PHP script ...

Utilize HTML search input to invoke a JavaScript function

I am currently facing an issue with a navbar form that I have created. The goal is to allow users to input either a 3 digit number or a 5 digit number, which should then trigger a function to open a specific link based on the input. However, I am strugglin ...

What is the best way to set up Storybook.js Webpack to support absolute image paths within CSS modules for a Next.js project?

I'm currently setting up Storybook to integrate with Next.js, Ant Design, Less, and TypeScript. In Next.js, images need to be stored in the public/ directory and linked using absolute paths for universal usage within the project. I am facing challenge ...

Implementing data updates in Vue.js within a Mongoose database, along with making API

I've encountered an issue where I need to update a count variable representing the votes each video receives after using GET and POST functions to retrieve and save URLs in my database. Additionally, I'm looking to disable the voting button once ...