Use jQuery to add and remove classes while opening and closing div elements individually

I am working on a page that contains hidden fullscreen divs. My goal is to be able to open these divs individually by clicking on the corresponding button and close them by clicking the "close" button inside the div.

Currently, I am able to open a div successfully, but when I try to close it, the next one automatically opens without giving me the option to close it.

Below is an excerpt of my code:

$(".button").click(function() {
    $(".overlay").addClass("overlay-open");         
    $(".closeoverlay").click(function() {   
        $("#overlay1").removeClass("overlay-open");
        $(".overlay").addClass( "overlay-close" );  
    });

To see a clearer demonstration, check out this Fiddle: http://jsfiddle.net/xq2gw50d/

Answer №1

It seems that the issue lies in having the closeoverlay click event nested within the button click event, causing a problem. Moving the closeoverlay click event outside of the button click should resolve this. See the updated code below for clarification:

HTML:

<a href="#" class="button" data-rel="overlay1" id="go1">Open Overlay 1</a>  
<a href="#" class="button" data-rel="overlay2" id="go2">Open Overlay 2</a>  
<div class="overlay" id="overlay1">Overlay 1
    <div class="closeoverlay">X</div>
</div>
<div class="overlay" id="overlay2">Overlay 2
    <div class="closeoverlay">X</div>
</div>  

JS:

$(".button").click(function () {
    var overlay = $(this).data('rel')
    $("#" + overlay).addClass("overlay-open");
});
$(".closeoverlay").click(function (e) {
    e.stopPropagation();
    $(this).closest('.overlay').removeClass("overlay-open");  
});

EDIT:

$(".button").click(function () {
    var overlay = $(this).data('rel')
    $("#" + overlay).addClass("overlay-open");
    $("#" + overlay).removeAttr("style");

});
$(".closeoverlay").click(function (e) {
    e.stopPropagation();
    $(this).closest('.overlay').fadeOut(function () {
        $(this).closest('.overlay').removeClass("overlay-open");
    });
});

JSFILLDE DEMO

Answer №2

Give this a shot

$("a").click(function(e) {
    var id = $(this).data('id');
    $("#"+id).removeClass('hidden').addClass("overlay-open");
});         
$(".closeoverlay").click(function() {   
    $(this).parent().removeClass("overlay-open");
    $(this).parent().addClass( "hidden" );  
});
.hidden{display:none;}
.overlay {
width: 100%;
height: 100%;
margin: 20px;
padding: 0;
background-color: #915E36;
position: fixed;
top: 0px;
z-index: 3;
float: left;
display: none;
background-position: center center;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}

.closeoverlay {
float: right;
width: 32px;
height: 32px;
padding: 10px;
background-image: url(../images/icon_close.png);
background-repeat: no-repeat;
cursor: pointer;
opacity: 1;

}

...

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="button" data-id="overlay1">Open Overlay 1</a>
<a href="#" class="button" data-id="overlay2">Open Overlay 2</a>

<div class="overlay" id="overlay1"> Overlay 1
<div class="closeoverlay">X</div> 
</div>

<div class="overlay" id="overlay2"> Overlay 2
<div class="closeoverlay">X</div> 
</div>

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

The MDL layout spacer is pushing the content to the following line

Here's an interesting approach to Material Design Lite. In this example from the MDL site, notice how the 'mdl-layout-spacer' class positions elements to the right of the containing div, giving a clean layout: Check it out <!-- Event ca ...

The website created with Mobirise's HTML is experiencing display issues after being uploaded to NGINX through PuTTY

Recently, I embarked on building a website using NGINX but realized it needed a major revamp. That's when I turned to Mobirise as my HTML expertise is limited. Here's the initial site I created: https://i.stack.imgur.com/IsCg4.jpg However, upon ...

Clicking on a radio button can trigger the selection of another radio button

I'm currently working on a form that includes 8 radio buttons - 4 for System A and 4 for System B. The options for the buttons are CF, ISO, ISO-B, and NW. My goal is to create a functionality where selecting a radio button in System A automatically se ...

Ways to expand flexbox to occupy the entire container

I have a scenario where I want two flexboxes in a container to fill the entire height of the container. The left flexbox should display an image that fills its entire space, while the right flexbox contains other content. However, I'm facing difficult ...

Ways to display additional selected values in a select menu

I have a basic form on my website that includes options like: Select 1 and Select 2. I would like to set it up so that if I select value Home in Select 1, the value in Select 2 changes to something like residence. How can I achieve this using a database? ...

Having difficulty retrieving the Area and Range information in ChartJS

I am new to working with HTML5 and ChartJS. I have noticed two different types of declarations when attaching JS Chart Versions 1.0.1 and 2.1.1. Can you please provide some insight into this? Additionally, I am facing an issue where the stripes behind the ...

What causes the unexpected outcome when applying theme overrides in Mui V5?

I am looking to adjust the border radius of all input fields in my project. Specifically, I would like the TextField component to have a border radius of https://i.stack.imgur.com/ULEGj.png instead of https://i.stack.imgur.com/NWmUe.png. According to the M ...

Ways to verify if an email has been viewed through the client-side perspective

How can I determine if an email has been read on the client side using PHP? I need to verify if emails sent by me have been opened by recipients on their end. Additionally, I would like to extract the following details from the client's machine: 1. ...

Ways to center items within a column using Bootstrap

I'm working on a React project with Bootstrap and I'm trying to align the contents of my second column to the bottom. However, everything I've tried so far hasn't been successful. I've seen others achieve this layout but for some r ...

What is the best way to populate an HTML array using my AWK script?

In my CGI script written in bash and HTML, I am attempting to display information from multiple CSV files in an HTML array. The following is the script I am using: #!/bin/bash echo "Content-type: text/html" echo "" echo ' <html> <he ...

jQuery menu animation not triggering until second click

I am currently working on implementing a menu that will slide in after clicking the hamburger button (located in the upper right corner). Instead of simply appearing, I wanted to use a jQuery function for a smoother sliding effect. However, I seem to be e ...

The jsTree rendering does not properly display the "closed" state of the JSON data nodes

Currently, I am in the process of setting up a jsTree instance to display a directory listing from a file server. However, I am encountering challenges with getting "sub-folder" or "sub-directory" nodes within the jsTree to show as open-able. Even though ...

When the HTML content matches a specific value, initiate a click event to trigger

Can anyone help me troubleshoot? I've tried multiple methods but can't seem to get it right. Here's a breakdown of what I'm attempting to accomplish: #info-NUMBER-btn shows Click to display more information. #info-NUMBER CSS is set t ...

What is causing FF and Chrome to not recognize these <form>'s?

My PHP logic is rendering the following forms with text inputs and a submit button. Everything works fine in IE, but in FF and Chrome, clicking the submit button reloads the page instead of going to the form action URL. I was surprised to find that the &l ...

Making a XMLHttpRequest/ajax request to set the Content-Type header

In my attempts, I have tested the following methods individually: Please note: The variable "url" contains an HTTPS URL and "jsonString" contains a valid JSON string. var request = new XMLHttpRequest(); try{ request.open("POST", url); request.set ...

Create a sleek 2-column design featuring a bonus scroll bar exclusively using CSS styling

In my current project, I have a unique challenge. I am working with a list of flattened div elements and unfortunately, I am unable to edit the HTML markup to add any structures. The first div in the list is quite long, and I would like to place it in a se ...

Insert the current row into the table

I'm working with an HTML table structure that looks like this: <table id="test"> <thead> <tr> <td></td> <td></td> <td></td> <td></td> ...

What is the best way to transform every record in a datatable into JSON format?

I have successfully converted datatable records to JSON using jQuery, however I am encountering an issue with the code. The current code only converts 10 records, which corresponds to the first page of the datatable. I have a total of 20 records spread acr ...

Sending data via POST when clicking on a jQuery UI autocomplete result

I'm attempting to send the id value of the selected item to the search.php file using POST. While it functions properly with GET, it does not work when using POST. Below is the code snippet I currently have: $( function() { $( ".search" ).autoco ...

CSS. Absolute positioning in relation to a div element

I discovered a way to adjust the positioning of a div using jQuery. Check out this example. Is it possible to achieve the same result using CSS? UPDATE: I came across this solution. I also want the horizontal window scrollbar to appear if the fixed elem ...