JavaScript powered simple window

I am currently working on a basic modal that will open and display content. Unfortunately, I cannot add images to help illustrate the design, so I'll do my best to describe it in detail.

The modal is linked to an image slider where the heading changes based on the displayed image. Clicking on the current image should trigger the modal to open.

Within the modal interface, there is a list on the left-hand side containing all the headings from the image slider. This allows users to easily switch between different contents within the modal.

My goal now is to ensure that when a user clicks on an image in the slideshow, the corresponding content opens in the modal, rather than just displaying the first item in the list of modal contents. (The modal content is stored in a collection)

I understand that this explanation might be confusing, and I would have included screenshots if possible to make it clearer.

Here lies my issue:


const displayContent = () => {
  headingString = currentHeading.textContent.toUpperCase();
  modalContentsCollection = modals[index].childNodes[1].children;
  choices = modalContentsCollection[0].querySelectorAll('li a');
  let compareArray = [];
  choices.forEach(element => {
    compareArray.push(element.textContent.toUpperCase().trim());
  });
  let b = false;
  console.log(compareArray);
  console.log(headingString);
  let c = 0
  while (!b && c < compareArray.length)  {
    console.log(compareArray[c]);
    console.log(c);
    if (headingString == compareArray[c]) {
      console.log(modalContentsCollection[c]);
      console.log(c);    
      modalContentsCollection[c].classList.toggle('show-toggle');
      console.log(modalContentsCollection[c]);
      b = true;
    c++;
  }
  modalContentsCollection[0].classList.toggle('show-toggle');
};

In an attempt to solve this problem, I created a function that compares the current heading with an array to determine the index of the modal content that needs to be displayed. However, I'm encountering issues with

modalContentsCollection[c].classList.toggle('show-toggle');
, as it doesn't seem to work within my loop. As a temporary workaround, I added
modalContentsCollection[0].classList.toggle('show-toggle');
to display the first item if no matching heading is found.

You can view some screenshots here: https://i.sstatic.net/ub48f.jpg Whenever "the image while Das Haus" is clicked, the modal should display the content related to "Das Haus". Similarly, clicking on "Wintersport" should show the content for that category, and so on.

Answer №1

After taking a break to go biking and have a snack, I came back with a fresh perspective and made some changes to the function above.

const displayContent = () => {
  console.log('displayContent');
  let headingString = currentHeading.textContent.toUpperCase();
  let modalContentsCollection = modals[index].childNodes[1].children;
  let choices = modalContentsCollection[0].querySelectorAll('li a');
  let compareArray = [];
  choices.forEach(element => {
    compareArray.push(element.textContent.toUpperCase().trim());
  });
  let i = 0;
  let bool = false;
  compareArray.forEach(element => {
    if (element === headingString) {
      modalContentsCollection[i].classList.toggle('show-toggle');
      bool = true;
      return;
    }
    i++;
  });
  if (!bool) {
    modalContentsCollection[0].classList.toggle('show-toggle');
  }
};

I'm not sure why this updated version is working now while the previous one wasn't. If anyone has any insights, please feel free to share them.

Thank you to everyone who offered help and support. Once this project is complete, I plan to share the source code for feedback and suggestions on a platform like exchangeoverflow.

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

Achieving horizontal scrolling for tables without using div wrappers

Whenever the width of tables in my articles exceeds the available space in the webpage layout, I wanted to enable horizontal scrolling. Despite trying to accomplish this with CSS alone, I was unsuccessful. As a result, I resorted to enclosing everything i ...

Top eCommerce frameworks optimized for Web2 and SaaS integration

Are there any payment and eCommerce frameworks that can seamlessly integrate with a REST-based application right out of the box? My server is Java-based, but I've found limited options in this area. I'm open to wrapping my interface with another ...

I am unable to engage with an element encapsulated within a #shadow-root that includes an <iframe> element

Original page source: Currently utilizing selenium with Java for web automation. In order to reach the shadow-root, I am utilizing JavaScriptExecutor (document.shadowRoot.querySelector) Successfully able to interact with various elements within the page ...

How can I link to a different field in a mongoDB Schema without using ObjectID?

I have created two schemas for books and authors: const bookSchema = new mongoose.Schema({ title: String, pages: Number, description: String, author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author' } }); const Book = mongoose.model ...

Why do my cards keep shrinking instead of moving to a new column when using flexbox and flex-flow?

I'm facing an issue with my flexbox that is causing my items to constantly shrink instead of moving to a new row. I've tried various solutions but nothing seems to work. I have removed the CSS for elements like headers that I believe are unrelate ...

Generate a fresh Date/Time by combining individual Date and Time components

I have set up a form to gather dates from one input box and times from another. var appointment_date = new Date(); var appointment_start = new Date("Mon Apr 24 2017 20:00:00 GMT-0400 (EDT)"); var appointment_end = new Date("Mon Apr 24 2017 21:30:00 GMT- ...

The value returned by a mocked Jest function is ignored, while the implemented function is not invoked

Having an issue with mocking the getToken function within my fetchData method in handler.ts while working with ts-jest. I specifically want to mock the response from getToken to avoid making the axios request when testing the fetchData method. However, des ...

I'm facing an issue with converting my object to an array as I keep getting the message: "ERROR TypeError: undefined

ERROR TypeError: undefined is not a function Why am I unable to convert my object to an array? This error keeps popping up as I attempt to map all the items that are currently objects but need to be converted into arrays for mapping. How can I accomplish ...

Exploring the capabilities of batch updates in Firestore with the latest web version-9

I am facing issues when trying to update certain values in my firestore collection within my nuxt project. const batch = writeBatch(firestore); const data = query(collection(firestore, `notifications`, `${uid}/news`)); const querySnapshot = await ...

Why is the `node-config` configuration undefined within a TypeScript Jest environment?

I have a TypeScript module that is functional in both development and production environments. It utilizes https://github.com/lorenwest/node-config. When I attempt to import it into Jest for testing purposes, I encounter an error suggesting that the config ...

Resizing Images Responsively Using Bootstrap

I'm working on specifying image sizes for different screen sizes. I'm wondering if there are any specific Bootstrap classes that only work at certain screen sizes. If so, it would be great because then I could use something like <img class = " ...

Tips for seamlessly incorporating WalletConnect into your decentralized app with the help of web3-react

I have been working on integrating WalletConnect into my project by referring to the documentation provided by web3-react. The configuration settings I am using for the connector are as follows: import { WalletConnectConnector } from '@web3-react/wal ...

Error: The variable "email" is not defined

Hey there, I could really use some assistance as a struggling developer. I've been at it all day trying to resolve this issue with no luck. It should be a simple task of posting from my AddUsers class and storing it in my SQL database. The state upda ...

Styling Radio Buttons and Links in Horizontal Layout Using Bootstrap

Encountering an issue in Bootstrap while attempting to incorporate custom radio buttons and a hyperlink in the same row. It seems that either the hyperlink functions OR the data-toggle feature for radio buttons works, but not both simultaneously, especiall ...

Web fonts are functioning properly only on Chrome and Safari for Macintosh operating systems

A web designer provided me with some fonts to use on a website. Below is the content of my fonts.css file: /* Font Awesome */ /* Font Awesome Bold */ @font-face{ font-family: 'font-awesome'; src: url('fonts/font-awesome-bold-webf ...

Struggling to understand JSON in joint.js?

I am trying to utilize the joint.js library to render a JSON data as a chart... let paper = new joint.dia.Paper({ el: $('#paper'), width: 600, height: 200, model: graph }); let graph = new joint.dia.Graph; let json = '{"em ...

Unable to differentiate between .jsx and .js files

Here is the content of my JavaScript file: var React = require('react'); export default class AmortizationChart extends React.Component { render() { var items = this.props.data.map(function (year, index) { ret ...

What is the Vercel equivalent to .netlify/functions?

I'm in the process of deploying this repository: https://github.com/DataStax-Examples/astra-tik-tok using Vercel instead of Netlify. I've converted vanilla React to Next.js, but I'm unsure how to transition the code in the Home.js file to w ...

What does React default to for the implementation of the ``shouldComponentUpdate`` lifecycle method in its components?

Having a personalized approach to the shouldComponentUpdate() method as part of the React component lifecycle is not obligatory. I am aware that it serves as a boolean function determining whether the render() function will be triggered by changes in comp ...

An error occurred while trying to load the XMLHttpRequest due to a NetworkError that was

I have encountered an issue while working on a client-side project using jQuery, JavaScript, and various jQuery plugins. Our professor supplied us with a proxy.php file to fetch the required data for our web application. I incorporated the easy tab plugin ...