Display various content in a modal based on the button that is clicked

I'm working on a simple modal that can be triggered by multiple buttons, but I need each button to load different content into the modal. Here are the links:

<a class="myBtn" href="#">Cats</a>

<a class="myBtn" href="#">Dogs</a>

and here are the content divs:

    <div id="myModal" class="modal">
                <!-- Modal content -->
                <div class="modal-content">
                    <span class="close"><img src="svg/close.svg"></span>
                    <div class="modal-header clearfix">
                        <h3">Cats</h3>
                    </div>
                    <div class="modal-body">
                        <h4>Content for Cats goes here.</h4>
                    </div>
                </div>
            </div>  

<div id="myModal" class="modal">
                <!-- Modal content -->
                <div class="modal-content">
                    <span class="close"><img src="svg/close.svg"></span>
                    <div class="modal-header clearfix">
                        <h3">Dogs</h3>
                    </div>
                    <div class="modal-body">
                        <h4>Content for Dogs goes here.</h4>
                    </div>
                </div>
            </div> 

Finally, here is the JS code:

<script type="text/javascript">
    
    // Get the modal
    var modal = document.getElementById("myModal");
    
    // Get the button that opens the modal
    var btn = document.querySelectorAll(".myBtn");
    
    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];
    
    [].forEach.call(btn, function(el) {
    // When the user clicks the button, open the modal 
        el.onclick = function() {
          modal+'me'.style.display = "flex";
        }
    })
    
    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
      modal.style.display = "none";
    }
    
    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
      if (event.target == modal) {
        modal.style.display = "none";
      }
    }
    </script>

If you have any suggestions on how to make the buttons unique so each one loads specific content into the modal, please share your solution. Thank you!

Answer №1

There are multiple solutions available.

'use strict';

const animalLinks = document.querySelectorAll('[data-animal-link]');
const animalModals = document.querySelectorAll('[data-animal-modal]');

document.addEventListener('click', (evt) => {
    evt.preventDefault();
    const target = evt.target;

    if (target && target.matches('[data-animal-link]')) {
        let value = target.dataset.animalLink;
        
        // check target
        console.log(value)

        animalModals.forEach((item) => {
            if (item.dataset.animalModal === value) {
                item.style.display = 'block';
            }
        });
    }
});
#myModal {
  display: none;
  width: 100px;
  height: 100px;
}

[data-animal-modal = 'cats'] {
  background-color: tomato;
}

[data-animal-modal = 'dogs'] {
  background-color: gold;
}
<a data-animal-link="cats" class="myBtn" href="#">Cats</a>
<a data-animal-link="dogs" class="myBtn" href="#">Dogs</a>

<div data-animal-modal="cats" id="myModal" class="modal"></div>
<div data-animal-modal="dogs" id="myModal" class="modal"></div>

This code is straightforward and can be customized for your specific tasks.

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

Generating JSON object in JavaScript by combining data from two arrays using specified keys

If, for instance, I were to have two arrays within JavaScript. The initial one possessing titles var titles = [ "welcome page", "how it works", "about us"] And the subsequent array containing the respective links to those pages var links = [ "/home", " ...

The capability to scroll within a stationary container

Whenever you click a button, a div slides out from the left by 100%. This div contains the menu for my website. The problem I'm encountering is that on smaller browser sizes, some of the links are hidden because they get covered up. The #slidingMenu ...

Google Map continues to update itself without needing to call render() again

In my current project, I am integrating Google Maps using ReactJS and Redux. However, whenever I interact with the map like clicking on a marker or zooming in, the entire map refreshes and turns gray before redrawing the same map with the marker. Even aft ...

A step-by-step guide for updating a minor version of Angular with Angular CLI

I've been searching online for the answer to this straightforward question, but can't seem to find it anywhere... In my angular 4 project (made with angular cli), I want to utilize the newly introduced http interceptors in version 4.3. Could so ...

vb.net form with client-side validation using jquery

I am facing an issue with a VB.NET form button that needs to go through jQuery validation before executing a function in the code behind. The problem is, regardless of whether the validation is true or false, the function stops and never calls the VB.NET f ...

Encountering the "ERPROTO" error message while attempting to send an Axios request from my REST API

I have set up my API at "localhost:3000/api/shopitems" and it successfully returns the JSON data below when accessed through a browser: [ { "item_available_sizes": { "s": 1 }, "imgs": { "album": [], ...

Building a dynamic tab menu using JavaScript: A step-by-step guide

In order to generate dynamic tab menus with JavaScript, I am seeking a solution that does not rely on jQuery as it may not be supported by all mobile devices. Any advice for replicating the same functionality using pure JavaScript would be greatly apprec ...

AJAX Username verification failing to validate

Working with PHP and MySQL, I created a basic form which includes a textfield for the username and a submit button. The page is named checkusername.php. Additionally, I implemented an AJAX function for handling this process. Subsequently, there is another ...

A step-by-step guide on implementing a callback function

I am eager to incorporate a callback into this script - specifically the third callback onSlideChangeStart(swiper) found at http://idangero.us/swiper/api/#.V9CMp5grJlY. Since I have never worked with callbacks before, I am unsure of where to begin. In es ...

Ways to determine if a website element is hidden from view

I am currently investigating the visibility of the following element: <ul class = 'pagination-buttons no-bullets'> https://i.sstatic.net/oOo7S.png When <ul class = 'pagination-buttons no-bullets'> is visible, its parent el ...

Utilizing Express.js to establish a connection with Twitter

Attempting to authenticate with Twitter using Express.js and Grant on my Windows 7 machine. Upon running node app.js in the command line, I encounter the following error: My main query is why 'MADE IT HERE' doesn't appear in the console ou ...

The Javascript Ajax loader gif is malfunctioning

I'm currently working on creating an Ajax loader gif using XMLHttpRequest. When I type something in the input field, a list of different words appears. This technique is commonly used in search engines as you type in the search box. However, I am als ...

The AngularJS Input Validation TypeError occurs when attempting to use an undefined function for validation

Currently, I am working on input validation using Angular. However, when the function is triggered, all elements return as undefined. The crucial code snippets are provided below, but do let me know if you need more information. Your assistance is greatly ...

Discovering the HTML5 Cache status through the utilization of Selenium's JavaScriptExecutor

How can I use Selenium's JavaScriptExecutor to retrieve HTML5 Cache status? I attempted the following code, but was unable to obtain the accurate status. import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import or ...

"Converting Text from a Streamed XML-Like File into CSV: A Step-by-Step Guide

I have log files that contain C++ namespace artifacts (indicated by the double colons ::) and XML content embedded within them. After loading and displaying the logs in a browser application, the content has been separated from the Unix timestamps like so: ...

What is the best approach for managing a response that lacks a body?

My current issue is that jQuery is attempting to parse the response body as JSON, but since the body is undefined, it causes an error. I am unable to modify the response, as this is the default response from Jenkins servers. It returns a 201, 404, or 500 ...

Is it possible to dynamically change HTML content by utilizing a JSON file?

Looking to implement a JavaScript loop (using jQuery) that can dynamically populate the HTML file with content from a JSON file based on matching <div> ids to the JSON "id" values. The solution should be scalable and able to handle any number of < ...

Return to previous page in a new tab with JavaScript

In my NextJS project, I have implemented a back button that calls the function handleClick when clicked. import { useRouter } from "next/router"; ... const router = useRouter(); const handleClick = e => { router.back(); } The functionality ...

There are a few steps to take in order to sort an array of objects by a

I want to organize and display data in a sortable table format javascript let dataList = [ { idx: number, name: string, btn: number, index: number }, { idx: number, name: string, btn: number, index: number }, { idx: number, name: string, btn: number ...

What is the best method to collect information from multiple AJAX requests?

In addition to synchronous AJAX calls, what is the most effective approach for handling a situation like this? var A = getDataFromServerWithAJAXCall(whatever); var B = getDataFromServerWithAJAXCallThatDependsOnPreviousData(A); var C = getMoreDataFromServe ...