Tips for creating multiple full-screen overlays in HTML

I am new to the world of web development and I am currently working on implementing a set of buttons that will trigger specific overlays when clicked. I found the following code snippet on W3schools which creates a button along with an overlay effect.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#overlay {
  position: fixed;
  display: none;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  z-index: 2;
  cursor: pointer;
}

#text{
  position: absolute;
  top: 50%;
  left: 50%;
  font-size: 50px;
  color: white;
  transform: translate(-50%,-50%);
  -ms-transform: translate(-50%,-50%);
}
</style>
</head>
<body>

<div id="overlay" onclick="off()">
  <div id="text">Text 1</div>
</div>

<div style="padding:20px">
  <h2>Overlay with Text</h2>
  <button onclick="on()">Button 1</button>
</div>

<script>
function on() {
  document.getElementById("overlay").style.display = "block";
}

function off() {
  document.getElementById("overlay").style.display = "none";
}
</script>
   
</body>
</html> 

I would like to make changes to this code in order to include another button that, upon being clicked, will show

<div id="text">Text 2</div>
within the overlay. Essentially, I want "Text 1" to be displayed when Button 1 is clicked, and "Text 2" to be displayed when Button 2 is clicked.

Answer №1

To achieve this, you can assign specific classes to your overlays in order to target them using JavaScript. It is also helpful to give each overlay a unique id for identification purposes.

<div class="overlay js-overlay" id="overlay-one" hidden>
  ...
</div>

Similarly, ensure that your buttons have identifiable classes as well. Utilize the value attribute to set the corresponding overlay's id within the button.

<button class="js-overlay-trigger" type="button" value="overlay-one">Open overlay</button>

In your JavaScript code, use document.querySelectorAll to select all buttons. Iterate through each button and attach an event listener for enhanced flexibility instead of using inline attributes like onclick.

Create a function that retrieves the value from the clicked button, which contains the overlay's id. Locate the overlay element based on the specified value and display it if found.

const triggers = document.querySelectorAll('.js-overlay-trigger');

function showOverlay(event) {
  const selector = event.target.value;
  const overlay = document.getElementById(selector);
  if (overlay !== null) {
    overlay.hidden = false;
  }
}

for (const trigger of triggers) {
  trigger.addEventListener('click', showOverlay);
}

In this example, the hidden attribute is used to display the overlay. Alternatively, you can manipulate CSS classes for the same effect, with the style property serving as a last resort.

Edit

Closing the overlays follows a similar approach. Select all overlays, loop through each, and attach an event listener to hide the respective overlay when triggered.

const overlays = document.querySelectorAll('.js-overlay');

function closeOverlay(event) {
  const overlay = event.currentTarget;
  overlay.hidden = true;
}

for (const overlay of overlays) {
  overlay.addEventListener('click', closeOverlay);
}

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

Lightbox2 is looking to reposition the caption to the right of the image

Can anyone help me understand how to move the caption, found in data-title, from underneath an image to the right of the image? I'm not very familiar with HTML/CSS, but it looks like the image is enclosed within a div called .lb-outerContainer, and t ...

Emphasize sections of text within a chart

Looking for a Specific Solution: I've encountered similar problems before, but this one has a unique twist. What I'm trying to achieve is to search for a substring within a table, highlight that substring, and hide all other rows (tr's) th ...

Stop automatic page refresh after submitting a jQuery post request

I've tried various solutions, but unfortunately, neither e.preventDefault() nor return false seem to be working for me. When I use prevent default ajax doesn't make post request. Even using $.post doesn't work as expected. Furthermore, addin ...

How can I submit a form or retrieve HTML content using JavaScript without using an iframe?

Background: My current job involves transcribing paper reports using a webapp that is quite old and cannot be updated or connected to a database directly. The system only checks for duplicate unique IDs once the entire form is submitted. This often leads ...

Error encountered: The Bootstrap Carousel function is causing a TypeError as e[g] is not defined

I am attempting to build a dynamic bootstrap carousel using my json data, and I have implemented jQuery-Template for rendering. Essentially, I am generating the carousel slider on-the-fly from my json data with the help of jQuery-Template. Here is a snippe ...

Challenges with Vue and the <noscript> element

I recently deployed a vue app and everything seems to be functioning as expected. However, I encountered an issue when trying to view the page source in any browser - the actual content is not visible and instead, the body section starts with a message ins ...

Refusing to cease downloading music on the local server through the embedded audio element

I was trying to setup background music on my website, but when I test it localhost, the music download instead of playing. However, when I tested with the full path, it played as expected. How can I prevent the download from happening in localhost? Here i ...

What could be causing the absence of any displayed content in FirBug when typing in the Google Search box?

Many websites with a suggestion box feature utilize AJAX requests to communicate with the server and receive responses. I attempted to intercept the requests made by the Google search box, but the FireBug console did not display anything. However, when us ...

I am experiencing difficulty in successfully transmitting a variable from my jQuery code to my PHP code

I've been attempting to pass a variable from my jQuery code to my HTML/PHP code using AJAX and POST. However, I'm encountering an error message stating "Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php on l ...

Maintain course focus when updating

I'm currently working on a to-do list where clicking on an item adds the "checked" class. However, when I refresh the page, everything reverts back to its original state without the checked class. How can I maintain the state of the checked items? I& ...

Learning about the functions Promise.all and Array.map()

My current project involves retrieving data from multiple APIs and aggregating them into a final array that will be displayed in the UI using React. Let me explain the scenario. First, I retrieve the main data from the primary API: const response = await ...

Arranging elements within an outer array by the contents of their inner arrays

I need help organizing an array based on the alphabetical order of a specific value within the inner arrays. For example: I want to sort this array by the prefix "old," so old A, old B, etc. const array = [ { personName: "Vans", personTags: ["young", " ...

Guide on implementing event listener for right click using pure JavaScript (VANILLA JS)

I need the div to appear wherever the cursor is holding down the right mouse button. In my scenario, I am using the following code: <div class="d-none" id="item"></div> #item{ position: absolute; top: 0; left: 0; w ...

Extract the HTML field value from an AJAX drop-down selection, rather than relying on user input

I have a field that allows users to select from a dropdown list using the following code: $(function() { $('.serial_number').live('focus.autocomplete', function() { $(this).autocomplete("/admi ...

Ways to eliminate or conceal solely the play/pause symbol or button from the media player within the video tag

[Please see the screenshot attached, I am looking to remove the play/pause icon that is highlighted] [screenshot] How can I hide or remove only the play/pause button from the media player of a video tag? When I dynamically add the controls attribute using ...

Create an array by copying elements from another array object

My goal is to merge the data from two arrays, array1 and array2, into a new array called array3. Here's how I want it structured: array 1 objects: userName, userId array 2 objects: userId, msg I aim to obtain an array3 consisting of: userId, userNa ...

how can I insert an asp textbox into a div using jquery?

I have an asp.net textbox (<asp:TextBox></asp:TextBox>), and I would like it so that when I click a button, the textbox is placed inside a div like this output (<div><asp:TextBox></asp:TextBox></div>). I tried using the ...

In situations where there may be a duplicate, what alternative can I utilize in place of the id attribute?

I understand that almost any element in the DOM can have an "id" attribute, and I've used it to track each client in a table of clients. Although ids should not be repeated, my rows are assigned unique identifiers based on each person's "clientId ...

django was unable to interpret the remainder: 'css/materialize.min.css' from 'css/materialize.min.css'

In following a tutorial, I am adding a chat bot UI that is embedded in Django. The file structure looks like this: . ├── db.sqlite3 ├── installDjango.sh ├── manage.py ├── rasadjango │ ├── asgi.py │ ├── __init__.p ...

Tips and tricks for stopping a jquery animation

I have created a hover effect for list items. When I hover over an item, it triggers an animation using the .animate() method. However, when I move my cursor away from the item, the hover animation continues until it reaches its end point. Is there a way ...