Upon clicking, a pop-up modal will display

I've set up a webpage with multiple cards displayed on it. My goal is to have a pop-up window appear when a user clicks on each card. Initially, I just want to ensure the basic functionality of the pop-up, even if the content remains the same. Although I managed to get the JavaScript code working using getElementById for a single card, this method won't suffice as there are multiple distinct cards involved here. Can someone assist me in getting this JavaScript feature to work as intended?

Below is my HTML:

<div class="cardContainer">
                <div class="trainingCard">
                    <div class="cardText"> 
                        <h1>How to fill out a time card</h1>
                        <p> To learn how to fill out a time card, click this card to access a digital training lesson!</p> 
                    </div>
                </div>

                <!-- next training card-->
                <div class="trainingCard">
                    <div class="cardText"> 
                        <h1>How to change labels</h1>
                        <p> To learn how to replace the labels in a labeler machine, click this card to access a digital training lesson!</p> 
                    </div>
                </div>
            <!-- next training card-->
                <div class="trainingCard">
                    <div class="cardText"> 
                        <h1>How to insert a trigger</h1>
                        <p> To learn how to insert a trigger when working on a liquid filling line, click this card to access a digital training lesson!</p> 
                    </div>
                </div>
            <!--end card container-->
            </div>


<div class="popUpModal" id=popUpModal>
    
    <div class="popUpContent">
        <div class="close">+</div>
        <h1 class="trainingPopUpHeader">How to Change Labels</h1>
        <div  class="trainingPopUpDescription">
            <p>When the labeler machine runs out of labels, it is up to one of the associates to replace the labels
             so the machine can continue running. It is important to be quick and accurate when reloading the labels. 
             Watch the video and read the step-by-step instructions to complete this training.    
            </p>
        </div>
        <div class= "trainingStepList">
            <p>
                1. Pull off used back paper <br>
                2. Find new pack of front & back labels <br>
                3. Insert front labels onto the front left roller <br>
                4. Insert back labels onto the front right roller <br>

            </p>
        </div>
        <video class="trainingVideo" controls>
            <source src="testVid.mp4">
        </video>

                        <!--add video element-->
                        <!--add step by step instructions-->
                                        
        <!--need a text header, a step by step instruction list, a video, and an input form for name-->
    </div>  


</div>

Given below is my CSS:

    .popUpModal{
    width: 100%; 
    height: 100%;
    top: 0;

    background-color: rgba(0,0,0,0.7);

    display: none;
    position: fixed;
    justify-content: center;
    align-items: center;
    text-align: center;
}

.popUpContent{
    width: 50%;
    height: 80%;
    padding-bottom: 20px;

    background-color: white;
    border-radius: 8%;

    display: inline-block;
    justify-content: center;
    vertical-align: center;
    position: relative;

    font-family: "Source Sans Pro",sans-serif;
}

.close{
    position: absolute;

    right: 5px;
    margin-right: 5%;

    font-size: 40px;
    transform: rotate(45deg);
    font-weight: bold;
    cursor: pointer;
}

.trainingPopUpHeader{
    margin-top: 4%;
    font-size: 40px;

    text-decoration: underline;
}

.trainingPopUpDescription{
    margin-top: 4%;
    margin-left: 10%;
    margin-right: 10%;

    font-size: 20px;
}

.trainingStepList{
    margin-left: 4%;

    font-weight:bold;
    text-align: left;
    font-size: 30px;
}

.trainingVideo{
    height: 25%;
    border-radius: 5%;
    margin-bottom: 3%;
}

Lastly, check out my JavaScript function which needs fixing:

    var modal = document.getElementsByClassName("popUpModal");
var trainingCard = document.getElementsByClassName("trainingCard");

trainingCard.onclick = function(){
    modal.style.display = "flex";
}

Answer №1

Let me illustrate with an abstract example. Imagine you want to show a modal multiple times by clicking different buttons. Firstly, you need to associate each button that triggers the modal. Your next aim is to customize the modal content based on the button clicked. One way to achieve this is by storing the context-specific content as a data attribute in each button. Then, you can retrieve this information and populate it within the modal.

abstract example

const btns = document.querySelectorAll('.btn-list button');
const m = document.querySelector('.modal');
btns.forEach(b => {
  b.addEventListener('click', (e) => {
    m.classList.remove('hide')
    const t = e.target.getAttribute('data-attribute');
    m.querySelector('p').innerHTML = t;       
  })
});

const close = document.querySelector('.close');
close.addEventListener('click', (e) => {
  m.classList.toggle('hide');
})
.modal {
  position: relative;  
  height:200px;
  width: 200px;
  background-color: green;
  color: white;  
  padding: 2px 10px;
  box-sizing: border-box;
}

.modal div {
  position: absolute;
  top: -10px;
  right:-10px;
  text-align:left;
  margin-top: auto;
  font-weight: bold;
  padding: 5px 10px;
  background: red;
  border-radius: 20px;
  cursor: pointer;  
}

.hide {  
  display: none;
}
<div class="modal">
  <p>MODAL</p>
  <div class="close">x</div>
</div>

<ul class="btn-list">
  <li><button data-attribute="text 1">1</button></li>
  <li><button data-attribute="text 2">2</button></li>
  <li><button data-attribute="text 3">3</button></li>
</ul>

Answer №2

The method known as "getElementsByClassName" allows you to retrieve multiple elements, also referred to as an HTMLCollection, essentially functioning as an array. It's important to note that you cannot directly assign functions like "onclick" or modify styles (which are not supported on these collections) to this collection. Instead, you must iterate through the collection and apply events to each individual item separately.

Answer №3

Your code includes a variable modal that holds a collection of HTML elements. You can only use modal.style.display = if modal is an individual HTML element. A simple fix is to change your approach by using:

var modal = document.getElementById("popUpModal");

by utilizing getElementById instead of getElementsByClassName. This will give you a single HTML element instead of a list of elements.

Another solution, suitable for multiple elements needing modification, is as suggested by digitalniweb, which involves iterating over all the popUpModals returned by getElementsByClassName, adjusting each modal to display flex. Refer to this stack overflow post for various ways to iterate through results from document.getElementByClassName (since it returns an HTML collection, traditional array looping methods may not always work efficiently, hence the mentioned alternative solutions).

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

Mobile device accessing a video file twice in a row

Currently, I am in the process of developing my own DRM solution for video content. Each time an access is made to the actual video file, it goes through a verification process. For example, instead of streaming video.mp4 directly, it first passes through ...

How can you identify a sign change in a JavaScript array?

I'm working with a JavaScript array and need some help. The array looks something like this: var exampleArr1 = [5,4,1,-2,-5,-7,5,1,2,-3,2,4...]; var exampleArr2 = [-5,-4,1,2,5,7,-5,1,2,3,-2,4...]; My goal is to create a function that can detect sign ...

What strategies can I use to ensure that the navigation bar is responsive when viewed on a

Check out my CSS file here for the navigation styling. See the screenshot of my HTML file showcasing the navigation panel here. I'm seeking assistance in making my navigation responsive on all mobile devices, as it is currently not functioning prope ...

Transforming API Response into a structured format to showcase a well-organized list

When I make an API call for a list of properties, the data comes back unorganized. Here is how the data from the API looks when stored in vuex: posts:[ { id: 1; title: "Place", acf: { address: { state: "Arkansas", ...

Formatting dynamically generated HTML using C#

My ASP.NET web forms site has a large menu that is dynamically generated using C# as a string. The HTML code returned looks something like this: <ul><li><a href='default.aspx?param=1&anotherparam=2'>LINK</a></li> ...

Can Material UI be utilized to design a Shopify e-commerce store?

As I prepare to create a Shopify storefront for the first time, I have a few inquiries. I have noticed how convenient it is to design both a mobile and desktop view using Material UI, but I have come across conflicting information online. Some sources su ...

What is the correct way to declare a new variable for a JSON object?

Within my Node JS application, I have an endpoint where I am attempting to retrieve data from two separate mongo collections. However, when trying to combine this data, I am encountering difficulties adding a new property to the JSON object. const getLesso ...

Efficiently incorporate a set of fields into a form and automatically produce JSON when submitted

The optimal approach for dynamically adding a set of fields and generating JSON based on key-value pairs upon form submission. <div class="container"> <div class="col-md-4"> <form method="POST" id="myform"> <div class="f ...

React displays an empty page when non-default routes are accessed in the build phase

<Router> <Switch> {console.log("Loading Routes")} <Route path="/booking" component={Booking} /> <Route path="/bookings" component={Bookings} /> <Route path=&quo ...

Unattaching Events in AngularJS

I'm still navigating my way through the realms of Angular and MVC programming, uncertain if I'm on the right track. There's a jQuery snippet that I wish to implement in some of my partials, but not all. With event listeners that persist eve ...

Modify URL parameters in Vue.js based on specific conditions to remove key-value pairs

Currently, I am working on a filter feature where I need to append query parameters to the URL based on user selections. If a user chooses a specific option, I want to modify the query string accordingly. Here's an example of my current URL structure: ...

Combining two containers in CSS

I am currently working on building a website design, and I have a menu positioned on the right side of the layout. Below is the code for the menu along with an explanation. #rightmenu { border-top: 1px solid #000000; border-right: 1px solid #00000 ...

How can I dynamically modify the class name of a specific element generated during an iteration in React when another element is clicked?

My goal is to dynamically add a class to a specific element within a table row when a user clicks a remove button. The desired behavior is to disable the entire row by adding a "removed" class to the containing row div. The challenge is that there are mult ...

Utilize the Bootstrap column push-pull feature on the mobile version of

https://i.stack.imgur.com/yTBIt.png When viewing the desktop version, div A is displayed at the top of the page. However, I would like to move it to the bottom when viewing on a mobile device (col-xs). I have attempted to solve this issue myself without s ...

Displaying information in Angular2

I'm currently facing an issue where I am unable to display certain information from my API in my view, even though the console is showing me that the necessary data is being retrieved. Below is a snippet of my Angular service: getById(id){ retu ...

Removing data with the click of a button

I have successfully implemented a feature where clicking the "add to my stay" button displays the name and price data. Subsequently, it automatically changes to a remove button when clicked again for another addon. If I press the remove button of the first ...

The Nuxt build is facing issues when connected to domains other than the root domain

Seeking assistance with the Nuxt.js build version, which is functioning properly on my main domain - for instance, my domain is test-domain.com. My build works well here, but on other connected domains like test2-domain.com, the _nuxt folder is not being ...

An HTML webpage that automatically refreshes but does't display the iframe content when the underlying HTML page is being updated

I have a script that updates a text file with completed tasks, creating log files in the process. I then use another script to format these logs with HTML code for tables, headings, banners, etc., saving the formatted version as Queue.html. To display this ...

Tips for selecting elements within the overflow container that are hidden:scroll

Is it feasible to fetch all elements located within the "hidden area" of a parent element that has an overflow:scroll property? A parent container, <div>, has a style of overflow:scroll;height:200px. Within this container is a table. Take a look at ...

NodeJS Promise fails to execute the third 'then()' method

One of the promises I have made involves logging into a website and gathering information. Here is the code I have written: var Promise = require('promise'); function login(user, pass){ // Code implementation for logging in and gathering in ...