The modal using HTML, CSS, and JavaScript is specifically designed to work with a

I am currently working on a school project and trying to create a modal, but I am facing some issues with its functionality.

html

 <div id="kw1cpraktijk">
        <img id="myImg" src="../assets/kw1cpraktijk.PNG">
        <h2>Practical Assignment P2</h2>
        <p>This is some text.</p>
    </div>
    <div id="willem2praktijk">
        <img id="myImg1" src="../assets/willem2praktijk.PNG">
        <h2>Project P1</h2>
        <p>This is some text.</p>
    </div>
    <div id="myModal" class="modal">
        <span class="close"> &times;</span>
        <img class="modal-content" id="img">
    </div>
css
    
#myImg

{
    
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
    width: 100%; 
    max-width:450px;
}




 .modal
    {
        display: none;
        position: fixed;
        padding-top: 100px;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0,0,0, 0.85);
    }
    
    .modal-content
    {
        margin: auto;
        display: block;
        width: 100%;
        max-width: 800px;
        animation-name: zoom;
        animation-duration: 0.6s;
    }
    
    @keyframes zoom
    {
        from {transform:scale(0)}
        to {transform:scale(1);}
    }
    
    .close
    {
        position: absolute;
        color: white;
        font-size: 50px;
        font-weight: bold;
        right: 35px;
        top: 0;
    }
    
    .close:hover
    {
        color: grey;
        cursor: pointer;
        text-decoration: none;
    }

javascript

var modal = document.getElementById("myModal");
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img");
var captionText = document.getElementById("caption");


img.onclick = function() {
    modal.style.display = "block";
    modalImg.src = this.src;
}

var exit = document.getElementsByClassName("close")[0];

exit.onclick = function() {
    modal.style.display = "none";
}

The current setup only works for the first image. It seems to be related to the JavaScript code as it runs only once. Any suggestions on what needs to be changed? Your help is greatly appreciated!

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut dignissim egestas lacus sit amet varius. Sed nec massa consectetur, posuere ex eget, convallis dui. Praesent aliquam leo nec metus tristique, vitae eleifend ex finibus. Pellentesque sagittis luctus eros, in placerat mauris efficitur id. Suspendisse ultricies sit amet lectus id rhoncus. Nam ligula quam, vulputate quis lacinia vitae, tempus sit amet risus. Duis lectus lectus, volutpat vitae justo at, pulvinar dignissim est. Nullam dignissim interdum dapibus. Duis commodo euismod lorem a posuere. Aliquam tincidunt iaculis vehicula. Nunc eget vestibulum velit. Vivamus tempor leo eget ex aliquam sollicitudin. Suspendisse sodales vel libero in fermentum.

Answer №1

Neither of the images are functioning properly due to the use of ID, which restricts the onclick function to target only one element. I suggest using class instead, allowing it to be applied to multiple elements. Please update your JavaScript code as follows:

var modal = document.getElementById("myModal");
var img = document.getElementsByClassName("myImg");
var modalImg = document.getElementById("img");
var captionText = document.getElementById("caption");

for (var i = 0; i < img.length; i++) {
  img[i].onclick = function() {
    modal.style.display = "block";
    modalImg.src = this.src;
  }
}

var exit = document.getElementsByClassName("close")[0];
exit.onclick = function() {
  modal.style.display = "none";
}

Don't forget to include the following in your HTML structure:

<div id="kw1cpraktijk">
    <img class="myImg" src="../assets/kw1cpraktijk.PNG">
    <h2>Praktijkopdracht P2</h2>
    <p>Some text here</p>
</div>
<div id="willem2praktijk">
    <img class="myImg" src="../assets/willem2praktijk.PNG">
    <h2>Project P1</h2>
    <p>More text goes here</p>
</div>
<div id="myModal" class="modal">
    <span class="close">×</span>
    <img class="modal-content" id="img"></div>

Answer №2

Your solution seems to be working fine!

It appears that your code is functioning properly for the first image, but there is an issue with the second image in your JavaScript - the code for the second image is missing.

I made some adjustments to address this problem without altering your existing code (Id and className).

Just a quick tip: using IDs can sometimes lead to issues, so it's usually better to manipulate HTML elements directly rather than showing a hidden div.

var modal = document.getElementById("myModal");
var img = document.getElementById("myImg");
var img2 = document.getElementById("myImg1");
var modalImg = document.getElementById("img");
var captionText = document.getElementById("caption");


img.onclick = function() {
modal.style.display = "block";
modalImg.src = this.src;
}
img2.onclick = function() {
modal.style.display = "block";
modalImg.src = this.src;
}

var exit = document.getElementsByClassName("close")[0];

exit.onclick = function() {
modal.style.display = "none";
}

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

PHP Mysqli - modifying data but encountering truncated items

I'm in the process of building a CRUD system, and I've encountered an issue on my edit page where the data being retrieved is getting cut off after the first space. For instance, if the company name in the database record is Stack Overflow, when ...

Google Chrome successfully transmits two variables with AJAX, whereas Mozilla Firefox does not send them

Having an issue with sending two values through ajax - currently only one value is being sent in Mozilla browser. Ajax script: $('#post_submit').click(function() { event.preventDefault(); var great_id = $("#post_container_supreme:first").attr(" ...

Troubleshooting Problems with CSS in Safari (Could Negative Margins be the

My problem lies specifically in Safari. Here is a screenshot of the issue: https://i.sstatic.net/amPeA.png To further investigate and experiment, I have created a fiddle at https://jsfiddle.net/hbadvb02/6/. Interestingly, the code works perfectly in Ed ...

The webpage is experiencing difficulty loading the image

Can someone help me troubleshoot an issue with loading an image in my HTML code? The image appears to have been sent but is not displayed. Could this be a CSS problem? (I am using materialized CSS) https://i.sstatic.net/sExue.png <html> {% extends ...

Encountering issues with the functionality of my Bootstrap navbar

After diving into the world of bootstrap, I encountered some challenges with the navigation bar in mobile view. Despite adding a navbar and a toggle button, it doesn't seem to be functioning correctly. Following tutorials and examples meticulously, bu ...

What is the best approach to slowly transition a value to a different one over a set period of time?

if(!isWalking) { isWalking = true; var animation = setInterval(function () {$player.css({'left': "+="+boxSize/25})}, 10); setTimeout(function(){clearInterval(animation)},250); setTimeout(function(){isWalking = false},250); ...

Encountering difficulty when attempting to send a POST request to Strapi version 4.5.6 through a Next.js frontend, resulting in a 400

I am currently developing an events application using nextJS and strapi. I'm facing a problem when attempting to send a POST request to my local strapi server from nextJS on my localhost, resulting in a 400 Bad Request status. The request is targeted ...

What are the reasons behind the inability to import an image file in Next.js?

Having an issue with importing image file in Next.js I'm not sure why I can't import the image file... The image file is located at 'image/images.jpg' In Chrome browser, there are no error messages related to the image, However, in ...

Is it possible to conceal a form field until a previous field has been completed?

Looking for a way to hide a form field until another field is properly completed? I have a divided registration form and want the second field to appear only when the first one is valid. Preferably using CSS3, with HTML5 and maybe some JavaScript if necess ...

Transforming basic text hyperlinks into HTML hyperlinks using regular expressions

I'm in search of a regular expression that can transform plain text links into HTML hyperlinks. Below are some sample links for testing: http://www.a-domain.com/something/?something www.a-domain.com/something/?something The regular expression must ...

Encountering a VueJS error when trying to locate a module while using a JSON file

I've been tasked with finding a solution to dynamically import pages within vuejs projects that are being built with a CLI tool by my team. I initially attempted to use functions as a string ("() => import(...)") and then evaluate that string, but ...

Struggling to find the accurate height of an element in React

Trying to display text in two rows using a React component. However, I am facing issues with getting the updated height of the element - it only shows the height after rendering. Below is my current component: constructor (props) { super(props) ...

Could you provide the parameters for the next() function in Express?

Working with Express.js to build an API has been a game-changer for me. I've learned how to utilize middlewares, handle requests and responses, navigate through different middleware functions... But there's one thing that keeps boggling my mind, ...

Tips on activating the CSS style while typing using the onChange event in React

Is it possible to dynamically adjust the width of an input as we type in React? Currently, my input has a default width of 1ch. I would like it to increase or decrease based on the number of characters entered, so that the percentage sign stays at the end ...

Ways to make an image wander aimlessly across a webpage while also spinning as it moves (with the help of jQuery or CSS)

I am working on making a div randomly move around a page. This is a related question Now, I have replaced the div with a picture like an "arrow" and I want it to randomly move while also pointing in the right direction by changing its rotation angle as i ...

Tips for creating dynamic rope animations with canvas and CSS3 styling

Interested in creating a canvas animation, or possibly using CSS3 for the same purpose. Looking to add an automatic rope animation, similar to it swaying gently. I've searched for scripts and other solutions, but haven't found anything suitable. ...

filtering elements with selectable functionality in jQuery UI

I'm trying to exclude the <div> children from being selected within this list item and only select the entire <li>. The structure of the HTML is as follows: <ul id="selectable"> <li> <div id="1"></div> ...

How come the transliteration feature isn't functioning properly when I try to input text into the second box?

<div class="row" v-for="(book, index) in Subsequent" :key="index"> <div class="col-md-8"> <div class="form-group label-floating"> <label class="control-label"> Details</label> <input type ...

Retrieving a list of selected items using React Material-UI

In my React + Material-UI frontend, there is a section where users can select items from a dropdown menu. I am looking for a way to capture the final list of items that the user selects, and allow them to delete items by clicking on a 'x'. How ca ...

Dealing with authentication problems when making jQuery AJAX requests

I have set up jQuery ajax calls to the server every 10 seconds on my webpage. However, I also want users to be automatically logged out if they remain idle for 2 minutes without making any requests. I have implemented form authentication cookies with a t ...