Issue with code: Only the most recent modal is being opened when multiple buttons are

Just starting out with coding and working on a web app. Trying to add two buttons at the top of the page - one for login/create an account and the other for adding reviews. Successfully implemented the first button, which displays a modal when clicked. However, when I tried to add the second button, both buttons ended up displaying the same modal.

Both modals have a small 'x' at the top right corner for closing them, but it doesn't work now. Here's a snippet of my code:

The CSS styles are defined in the head section.

    /* The Modal (background) */
    .modal {
        display: none;
        position: fixed;
        z-index: 1;
        padding-top: 100px;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgb(0,0,0);
        background-color: rgba(0,0,0,0.3); /* Used to grey out the rest of the screen */
    }

    /* Modal Content */
    .modal-content {
        background-color: #fefefe; /* Background colour of Modal */
        margin: auto;
        padding: 20px;
        border: 1px solid #888;
        width: 50%;
    }

    /* The Close Button */
    .close {
        color: #aaaaaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
    }

    .close:hover,
    .close:focus {
        color: #000;
        text-decoration: none;
        cursor: pointer;
    }
</style>

The actual HTML code is inside the body section.

<h2>Modal Testing</h2>

<!-- Buttons to open Modals -->
<button id="loginBtn">Account</button>
<button id="reviewBtn">Add Review</button>

...

Answer №1

When you use JavaScript within different <script> tags, it doesn't necessarily mean they are separate blocks – rather, they get appended to each other. This can lead to issues like variable overwriting, for example if you declare a Variable modal in one block and then again in the second block, the Variable will be overwritten. To prevent this, I have changed the Var names to XXX1 and XXX2.

function visible(){
    var x = document.getElementById("userInput");
    if (x.type === "password") {
        x.type = "text";
    } else {
        x.type = "password";
    }
}

// Get the modal
var modal1 = document.getElementById('loginModal');

// Get the button that opens the modal
var btn1 = document.getElementById("loginBtn");

// Get the <span> element that closes the modal
var span1 = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn1.onclick = function() {
    modal1.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span1.onclick = function() {
    modal1.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal1) {
        modal1.style.display = "none";
    }
}

// Get the modal
var modal2 = document.getElementById('addReviewModal');

// Get the button that opens the modal
var btn2 = document.getElementById("reviewBtn");

// Get the <span> element that closes the modal
var span2 = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn2.onclick = function() {
    modal2.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span2.onclick = function() {
    modal2.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal2) {
        modal2.style.display = "none";
    }
}
    .modal {
        display: none;
        position: fixed;
        z-index: 1;
        padding-top: 100px;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgb(0,0,0);
        background-color: rgba(0,0,0,0.3); /* Used to grey out the rest of the screen */
    }

    /* Modal Content */
    .modal-content {
        background-color: #fefefe; /* Background colour of Modal */
        margin: auto;
        padding: 20px;
        border: 1px solid #888;
        width: 50%;
    }

    /* The Close Button */
    .close {
        color: #aaaaaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
    }

    .close:hover,
    .close:focus {
        color: #000;
        text-decoration: none;
        cursor: pointer;
    }
<h2>Modal Testing</h2>

<!-- Buttons to open Modals -->
<button id="loginBtn">Account</button>
<button id="reviewBtn">Add Review</button>

<!-- The Modals -->

<!-- Login/Create Account Modal -->
<div id="loginModal" class="modal">

<!-- Modal content -->
<div class="modal-content">
    <span class="close">&times;</span>
    <p>Login details</p>
    <!-- Allows the user to input information-->
    <form action="/action_page.php">
        Username:<br>
        <input type="text" name="username" value="">
        <br>
        Password:<br>
        <input type="password" value="" id="userInput">
        <br><br>
        <input type="checkbox" onclick="visible()">Show Password
    </form>
    <button id="signInBtn">Sign In</button>
    <p>Not got an account? Sign up now!</p>
    <button id="signUpBtn">Sign Up</button>
    <button id="cancelBtn">Cancel</button>

</div>

</div>

<!-- Add Review Modal -->
<div id="addReviewModal" class="modal">

<!-- Modal content -->
<div class="modal-content">
    <span class="close">&times;</span>
    <p>Add Review</p>
    <!-- Allows the user to input information-->
    <form action="/review_page.php">
        Location:<br>
        <input type="text" name="location" value="">
        <br>
        Comments:<br>
        <input type="text" name="comments" value="">
        <br>
    </form>
    <button id="submitBtn">Submit Review</button>
    <button id="cancelBtn">Cancel</button>

</div>

</div>

With these changes, the buttons now open their corresponding modals as intended.

If I find a solution to the "Close on X" functionality, I'll update you here.

Apologies for any language barriers, I hope my explanation was clear enough :)

Answer №2

try this instead

modal.getElementsByClassName("close")[0];

for this code snippet

document.getElementsByClassName("close")[0];

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

Unlock the power of Shopify's API using node.js and React. Learn how to seamlessly read and write to the Shopify App API

I have recently delved into coding and Shopify, with some experience in fetching APIs using vanilla JavaScript. However, I find myself struggling to grasp the concept when it comes to node.js and React. Despite my best efforts to study the documentation, e ...

What is the best way to save a large array to a .txt file in node.js?

It seems that using fs.writeFile is the obvious solution. However, after reading the response to this question, it appears that a Stream technique might be more appropriate. In an attempt to delete a line from a text file by converting it to an array, I ...

The nodejs server failed to respond to my request, displaying "undefined" instead

I have encountered some challenges while hosting my website on Firebase and Heroku Here are the issues I am facing: Initially, I am encountering CORS errors when trying to post data from a Firebase hosted URL to a server hosted on Heroku Even after re ...

Discrepancy in the vertical pattern repetition of the SVG background

When I use a simple div with an SVG set as a background image with vertical repeat, I noticed a gap of varying sizes on Chrome and Firefox depending on the screen size (please resize the window). Check out the issue here .bg { width: 50%; height: 2 ...

Timer for searching webpages using Javascript

I am looking for a way to continuously search a specific webpage for a certain set of characters, even as the text on the page changes. I would like the program to refresh and search every minute without having to keep the webpage open. In addition, once ...

Changing a string to uppercase and lowercase

I am currently working on a software that takes a string, divides it, capitalizes the first letter of the first string, and capitalizes all letters in the second string. Below is the code snippet: var fullName = "ThEoDORe RoOseVElT"; function nameEditor( ...

(Angular) Employing *ngFor directive for populating a table

I am in need of a table structure that resembles the following: https://i.sstatic.net/rB2C6.png To achieve this, I am utilizing a basic Bootstrap table along with Angular's *ngFor. Each cell in the table should display a different name from an array ...

Tips on how to ensure a function in jQuery completes before executing another function

My query relates to a div called "#ImageBingingDiv" that is initially set to display:none. I use a fadeIn effect and then adjust the HTML content to include an image. However, when trying to add elevateZoom to the image tag, it doesn't work as intende ...

Angular: A guide to binding to the required/ngRequired attribute

There is a directive that may or may not be required, and it can be used in two different ways. <my-foo required></my-foo> or <my-foo ng-required="data.value > 10"></my-foo> Even though require and ngRequire are essentially t ...

Overlap and cover additional elements within a DIV

I am looking to create a versatile function that can effortlessly overlay various elements such as selects, textfields, inputs, divs, tables, and more with a partially transparent div matching their exact height and width. I have managed to obtain the pos ...

The last javascript file that was included has been overlooked

When using jqplot, I noticed that the last included plugin is being ignored. If I switch their positions, the first to last one works while the last one does not. There are no errors in the console to indicate what might be going wrong. Moving the canvasOv ...

Issue with Django URLs: Error when trying to match routes

I have recently made changes to some of the URLs in my app, and now I am encountering an error when trying to render my index page. Can someone help me identify the issue? I have already checked for typos in my HTML file. The error message I am receiving i ...

What is the best way to incorporate CSS animations into JavaScript for mobile devices?

I need a way to copy text to the clipboard and show an alert confirming that it was copied successfully. When the user clicks/touches the coupon PRIMEIRACOMPRA, the text "cupom copiado" changes its opacity to 1 and runs an animation to hide it. See Examp ...

Customizing HTML element tags in MUI: Best practices

Using the most recent version of MUI (v5) and incorporating CssBaseline from @mui/materials. Typically, in CSS, I would set up my styles like this: body, html, #root { width: 100%; height: 100%; min-height: 100%; margin: 0; padding: 0; font-siz ...

Preventing jQuery plugin from loading in Ajax response

When I receive an AJAX response from page 2, I want to load the jQuery rating plugin on page 1. Although I obtained data from a database, I am unable to load the rating plugin. Here is my script: temp1.php <script type="text/javascript" src="review-p ...

Extract the color of an individual character

There is a code snippet in JavaScript using p5.js that functions as a video filter: const density = ' .:░▒▓█' //const density = ' .tiITesgESG' //let geist; let video let asciiDiv let playing = false let ...

I am having issues with Tailwind CSS overriding the responsive padding on my website

I'm currently working on implementing responsive padding for a component. Given that Tailwind CSS follows a mobile-first approach, I have set the mobile padding to p-3, while screens at "md" and larger widths should use p-5. However, it seems like the ...

Changing the color of Material UI pagination: a step-by-step guide

I have integrated Material UI to create a pagination bar for my website. While everything is functioning properly, I am looking to personalize the appearance. After reviewing their documentation, I tried implementing a theme but encountered an issue with c ...

Retrieve JSON information from the driver's console using Selenium with Python

I am trying to retrieve JSON data from the console, which is shown in this image. Here are the codes I have used so far: j = driver.execute_script(" return document.getElementsByClassName('form-group text required assessment_questions_choices_text ...

Using bootstrap can alter the positioning of elements that have margins relative to other elements

After exploring suggestions from my previous post on Stack Overflow, I have implemented a modified version to animate drag movements. While the HTML5 draggable attribute can achieve dragging, its limitations and side effects are something I aim to avoid. ...