How can I make a single block expand and have the option to uncheck it by clicking again?

Currently, I am in the process of creating a small program for a website where I intend for certain blocks to expand almost to the size of the window when clicked on to reveal text. Unfortunately, using checkboxes seems to cause all boxes to grow, and with radios, there is an issue where clicking does not make them disappear.

.games {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  /* background-color:  rgba(0, 0, 47,0.3); */
  justify-content: space-evenly;
}

.games:has(input:checked) .game-list {
  width: 50vw;
  height: 100vh;
  margin: 50px;
}

.game-list {
  margin: 30px;
  ;
  padding: 20px;
  height: 275px;
  width: 325px;
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1px solid gray;
  background: rgba(255, 75, 255, 0.1);
  box-shadow: 0 8px 40px 0 rgba(45, 57, 231, 0.37);
  backdrop-filter: blur( 4px);
  -webkit-backdrop-filter: blur( 4px);
  border-radius: 10px;
  border: 1px solid rgba( 255, 255, 255, 0.18);
}

.game-list:hover {
  transform: scale(1.05);
}
<div class="games">
  <label for="Chapter 1">
          <div class="game-list">
            <input type="checkbox" hidden id="Chapter 1">
            <img src="https://rideawavedesign.com/wp-content/uploads/2021/06/dnd-dice-level-up-birthday-card-1.jpg" style="width:140px; height: 140px;"/ >
          <h1 style=" color:#FFFFFF">Chapter 1: </h1>
          <p style=" color:#FFFFFF; font-size: 20px">Step-by-Step</p>
          </div>
          </label>
  <label for="Chapter 2">
            <div class="game-list">
              <input type="checkbox" hidden id="Chapter 2">
              <img src="https://miro.medium.com/v2/0*ggxUIJLB6dBwLHKo.jpg" style="width:140px; height: 140px;"/>
            <h1 style=" color:#FFFFFF">Chapter 2: </h1>
            <p style=" color:#FFFFFF; font-size: 20px">Races</p>
          </div>
          </label>
  <label for="Chapter 3">
            <div class="game-list">
              <input type="checkbox" hidden id="Chapter 3">
              <img src="https://miro.medium.com/v2/resize:fit:1080/1*Z_eV_OUsPV359E-ZUb-dbw.jpeg" style="width:140px; height: 140px;"/>
            <h1 style=" color:#FFFFFF">Chapter 3: </h3>
            <p style=" color:#FFFFFF; font-size: 20px">Classes</p>
          </div>
          </label>
  <label for="Chapter 4">
            <div class="game-list">
              <input type="checkbox" hidden id="Chapter 4">
              <img src="https://www.greenmangaming.com/blog/wp-content/uploads/2020/01/DnD-Alignments.png" style="width:140px; height: 140px;"/>  
            <h1 style=" color:#FFFFFF">Chapter 4: </h1>
             <p style=" color:#FFFFFF; font-size: 20px">Personality and Background</p>
          </div>
          </label>
  <label for="Chapter 5">
            <div class="game-list">
              <input type="checkbox" hidden id="Chapter 5">
              <img src="https://i.pinimg.com/736x/da/bb/c5/dabbc5d29cb413808c9bd61fbbef822d.jpg" style="width:140px; height: 140px;"/>  
            <h1 style=" color:#FFFFFF">Chapter 5: </h1>
             <p style=" color:#FFFFFF; font-size: 20px">Equipment</p>
          </div>
          </label>
  <label for="Chapter 6">
            <div class="game-list">
              <input type="checkbox" hidden id="Chapter 6">
              <img src="https://i.postimg.cc/TP6zYYcx/Multiclass.webp" style="width:140px; height: 140px;"/>
            <h1 style=" color:#FFFFFF">Chapter 6: </h1>
            <p style=" color:#FFFFFF; font-size: 20px">Customization options</p>
          </div>
          </label>

I have made several attempts by using different hidden IDs and labels, but regardless of the configurations, it appears that all boxes end up enlarging simultaneously.

Answer №1

If you're looking to enlarge a clicked image while simultaneously shrinking any previously selected images back to their original size, there is a simple solution. You can achieve this by using radio inputs and assigning them the same name attribute (in this case, name="chapter"). This way, only one input can be selected at a time. Additionally, I applied the game-list:has(input:checked){...} style as recommended earlier.

.games {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-evenly;
  }
  
  .game-list:has(input:checked){
    width: 50vw;
    height: 100vh;
    margin: 50px;
  }
  
  .game-list {
    margin: 30px;
    padding: 20px;
    height: 275px;
    width: 325px;
    display: flex;
    flex-direction: column;
    align-items: center;
    border: 1px solid gray;
    background: rgba(255, 75, 255, 0.1);
    box-shadow: 0 8px 40px 0 rgba(45, 57, 231, 0.37);
    backdrop-filter: blur(4px);
    -webkit-backdrop-filter: blur(4px);
    border-radius: 10px;
    border: 1px solid rgba(255, 255, 255, 0.18);
  }
  
  .game-list:hover {
    transform: scale(1.05);
  }
<div class="games">
  <label for="Chapter 1">
          <div class="game-list">
            <input type="radio" name=chapter hidden id="Chapter 1">
            <img src="https://rideawavedesign.com/wp-content/uploads/2021/06/dnd-dice-level-up-birthday-card-1.jpg" style="width:140px; height: 140px;"/ >
          <h1 style=" color:#FFFFFF">Chapter 1: </h1>
          <p style=" color:#FFFFFF; font-size: 20px">Step-by-Step</p>
          </div>
          </label>
  <label for="Chapter 2">
            <div class="game-list">
              <input type="radio" name=chapter hidden id="Chapter 2">
              <img src="https://miro.medium.com/v2/0*ggxUIJLB6dBwLHKo.jpg" style="width:140px; height: 140px;"/>
            <h1 style=" color:#FFFFFF">Chapter 2: </h1>
            <p style=" color:#FFFFFF; font-size: 20px">Races</p>
          </div>
          </label>
  <label for="Chapter 3">
            <div class="game-list">
              <input type="radio" name=chapter hidden id="Chapter 3">
              <img src="https://miro.medium.com/v2/resize:fit:1080/1*Z_eV_OUsPV359E-ZUb-dbw.jpeg" style="width:140px; height: 140px;"/>
            <h1 style=" color:#FFFFFF">Chapter 3: </h3>
            <p style=" color:#FFFFFF; font-size: 20px">Classes</p>
          </div>
          </label>
  <label for="Chapter 4">
            <div class="game-list">
              <input type="radio" name=chapter hidden id="Chapter 4">
              <img src="https://www.greenmangaming.com/blog/wp-content/uploads/2020/01/DnD-Alignments.png" style="width:140px; height: 140px;"/>  
            <h1 style=" color:#FFFFFF">Chapter 4: </h1>
             <p style=" color:#FFFFFF; font-size: 20px">Personality and Background</p>
          </div>
          </label>
  <label for="Chapter 5">
            <div class="game-list">
              <input type="radio" name=chapter hidden id="Chapter 5">
              <img src="https://i.pinimg.com/736x/da/bb/c5/dabbc5d29cb413808c9bd61fbbef822d.jpg" style="width:140px; height: 140px;"/>  
            <h1 style=" color:#FFFFFF">Chapter 5: </h1>
             <p style=" color:#FFFFFF; font-size: 20px">Equipment</p>
          </div>
          </label>
  <label for="Chapter 6">
            <div class="game-list">
              <input type="radio" name=chapter hidden id="Chapter 6">
              <img src="https://i.postimg.cc/TP6zYYcx/Multiclass.webp" style="width:140px; height: 140px;"/>
            <h1 style=" color:#FFFFFF">Chapter 6: </h1>
            <p style=" color:#FFFFFF; font-size: 20px">Customization options</p>
          </div>
          </label>

Answer №2

It is quite challenging for me to determine your exact goal based on the provided code. However, it seems like you may be aiming for something along these lines.

This revised version adheres to valid markup practices and has been enhanced for better clarity. To ensure the validity of your markup, you can utilize tools such as the W3C Markup Validator.

There are several key points that need to be addressed, so this response may be quite extensive:

  1. I have converted your cards into sections to improve the semantic validity of the markup structure.
  2. The paragraph (<p>) has been replaced with a subheadline (h2) since a chapter's title should be distinguished from a regular paragraph.
  3. A "wrapper" element has been introduced as a generic container for managing the toggle functionality of text content, aiding in maintaining focus.
  4. Various attributes have been added to assist users with disabilities who rely on screen readers or keyboard navigation when expanding elements, including aria-expanded="false" to indicate a collapsed state, tabindex="0" for keyboard focus, and role="button" to highlight clickable elements for assistive technologies.
  5. Your CSS styles have been refined and renamed to align with the updated HTML structure. Instead of using CSS hacks, the :focus pseudo-selector has been replaced with [aria-expanded="true"] to target expanded cards more effectively.
  6. All inline styles have been removed and consolidated within the CSS stylesheet for improved organization.
  7. To display clicked elements in fullscreen mode while revealing additional details, the wrapper element has been styled with position: fixed; inset: 0; to cover the entire screen with appropriate padding and margin. An overflow rule overflow-y: auto has also been included to handle long text passages exceeding the screen height.

Moving on to the JavaScript section, I will provide an overview without delving into intricate details to avoid overwhelming you at this stage. As you progress in mastering CSS, HTML, and eventually delve into JavaScript, you can explore these concepts further. It appears that there is still some distance to cover before diving deep into JavaScript. Remember, continuous learning is essential, especially when exploring advanced subjects like responsive web design, accessibility, user experience, SEO considerations, and performance optimization.

window.addEventListener('DOMContentLoaded', function() {
  // Your script logic here
})

The above snippet utilizes addEventListener to wait for a specific event (such as DOMContentLoaded) before executing a defined function. This mechanism ensures that all DOM elements are loaded before script execution, preventing potential errors related to accessing null elements prematurely.

const Wrappers = document.querySelectorAll('.wrapper');

The code snippet declares a constant named Wrappers and retrieves a collection of elements matching the specified CSS selector '.wrapper'.

Wrappers.forEach(temporaryVariable => {
  temporaryVariable.addEventListener('click', function() {
    // Event handling logic goes here
  })
});

In this block of code, the forEach method is utilized to iterate through each element in the 'Wrappers' collection. An event listener is attached to each element, waiting for a 'click' event to trigger a corresponding function.

let selectedElement = this.closest('.wrapper');
let expandedState = selectedElement.getAttribute('aria-expanded') === 'true';
selectedElement.setAttribute('aria-expanded', String(!expandedState));

In the given JavaScript snippet, a variable is declared using let. The this.closest('.wrapper') statement selects the closest ancestor element matching the '.wrapper' selector. When checking the 'aria-expanded' attribute, we convert its value to a boolean for proper toggling of the expanded state.

window.addEventListener('DOMContentLoaded', function() {
  const Wrappers = document.querySelectorAll('.wrapper');
  Wrappers.forEach(wrapper => {
    wrapper.addEventListener('click', function() {
      let selectedElement = this.closest('.wrapper');
      let expandedState = selectedElement.getAttribute('aria-expanded') === 'true';
      selectedElement.setAttribute('aria-expanded', String(!expandedState));  
    })
  })
})
* {
  box-sizing: border-box;
}

body {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-evenly;
}

.wrapper[aria-expanded="true"] {
  background-color: white;
  position: fixed;
  inset: 0;
  padding: 50px;
  overflow-y: auto;
  z-index: 100;
}

.wrapper[aria-expanded="true"] section {
  width: auto;
  height: auto;
}

.wrapper[aria-expanded="true"] p {
  display: block;
}

section {
  margin: 30px;
  padding: 20px;
}

If SASS, an advanced CSS preprocessor, were applied, the CSS code could be optimized and structured with nesting capabilities:

* {
  box-sizing: border-box;
}

body {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-evenly;
}

.wrapper {
  &[aria-expanded="true"] {
    background-color: white;
    position: fixed;
    inset: 0;
    padding: 50px;
    overflow-y: auto;
    z-index: 100;

    section {
      width: auto;
      height: auto;
    }
    p {
      display: block;
    }
  }
}

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

jQuery code tailored specifically for desktop use

Hello, I could use some assistance with a jquery script. I have been able to accomplish what I need using a jquery script, but I would like it to only work on desktops and be disabled on tablets and mobile devices. The script I am currently using is as fo ...

How can we determine the total character count of a file that has been loaded into a textarea

I have a textarea where I can count the number of characters as I type. function calculateCharacters(obj){ document.getElementById('numberCount').innerHTML = obj.value.length; } <textarea name="textField" id="my_textarea" class="text_edit ...

How to remove an event listener when e.target points to a hyperlink

element, I encountered an issue using a slideshow component sourced from our components library. This component receives swipe events from a utility function that is initialized upon mounting. The problem arose while testing on a mobile phone - tapping a ...

What is the best way to extract numbers from a string using JavaScript?

I am working with a string in javascript that looks like this: var xyz= "M429,100L504.5,100L504.5,106L580,106L570,98M580,106L570,114"; My goal is to extract the numbers and store them in an array. I attempted the following code: var x=xyz.match(/\ ...

What is the best way to trigger a jQuery function after adding a <div> element through Ajax loading?

When I use Ajax to append a <div>, the dynamic inclusion of jQuery functions and CSS for that particular <div> does not seem to work. The insertion is successful, but the associated jQuery functions and CSS do not load properly. How can this be ...

Tips for effectively utilizing an if/else structure to animate fresh content from the right while smoothly removing old content by sliding it to the left

document.getElementById("button1").addEventListener("click", mouseOver1); function mouseOver1(){ document.getElementById("button1").style.color = "red"; } document.getElementById("button2").addEventListener("click", mouseOver); function mous ...

Surprising behavior of translateZ in Framer Motion

Trying to position elements in a circular layout has led to unexpected behavior when using framer motion's translateZ. By applying styles with a template literal without shorthand for transforms, the desired effect is achieved: transform: ` rotateY( ...

Is there a simpler method to enable built-in CSS-Sass in Next.js without the need for excessive configuration?

Is there a way to maintain the built-in CSS/SASS feature in Next.js without extensive configuration? Utilizing the built-in CSS/SASS is convenient, but introducing less to next.config.js triggers the disabling of this feature, requiring manual configurati ...

What is the best method for eliminating shading on sub-tabs in R Shiny?

Currently, I am in the process of developing a user-friendly interface with senior tabs and sub-tabs underneath to guide users through various options. To better assist users in navigating these choices, I have implemented a system where inactive senior ta ...

Is there a way to stylize the initial words of a brief text block by blending small caps with italics, all while avoiding the use of a span tag?

I have a series of images with numbered captions like "Fig. 1", "Fig. 2", "Fig. 3", followed by a brief description on the same line. Is there a way to programmatically style these strings (the “Fig. #” only) using CSS or Javascript to make them italic ...

Selecting a language by clicking on it

I recently designed a bootstrap navigation bar for my website and incorporated a language selection dropdown menu into it. <li class="nav-item dropdown"> <a class="nav-link dropright" href="#" id="navbarDropdown" role="button" data-toggle="dr ...

Get the PDF in a mobile app using HTML5 and Javascript

For my HTML5/JavaScript-based mobile application, I am in need of implementing a feature that enables users to download a PDF file. The PDF file will be provided to me as a Base64 encoded byte stream. How can I allow users to initiate the download proces ...

Tips for live streaming a canvas element using WebRTC

While researching about WebRtc, I stumbled upon this amazing project on GitHub: https://github.com/mexx91/basicVideoRTC I have successfully tested the communication between 2 cameras using node.js. Is it possible to capture a stream from getUserMedia, m ...

Guide: Previewing uploaded images with HTML and jQuery, including file names

Any constructive criticism and alternative methods for accomplishing this task are welcomed. I am currently working on writing jQuery code that will allow users to preview file(s) without reloading the DOM. To achieve this, I have been using .append() to ...

Customize the color of the horizontal line in React using dynamic properties

Is there a way to customize the color of an <hr /> element in a React application? If we were to use a functional component to accomplish this, how would we go about it? ...

Steps for adding a ::after border to a div

Looking for a way to create a border line separator between the top and bottom sections? I've been struggling with this task, but I have managed to make progress by adding a white line. However, I'm facing an issue where the container's widt ...

Unexpected appearance of DOM elements

I've come across an unusual bug in a web application I've been developing that is reproducible in Chrome and Safari, but not in Firefox. To witness the bug, go to www.lastcalc.com and type a single uppercase letter. The letter will be immediatel ...

Putting the second line of a list in a paragraph element with indentation (excluding UL or OL)

I am working with a table that has the following structure: html { width: 400px; } <table> <tr> <td>Description:</td> <td style="white-space: pre-wrap;"> Some text which could be quite long with some &apos ...

Angular 6 and Bootstrap 4 unite in a powerful collaboration, showcasing a stunning carousel feature enhanced with dynamic

Currently I am working on creating a carousel using Bootstrap 4 and Angular 6. Everything is functioning properly, except for one issue that I am facing. I am trying to add Indicators dynamically by using a *ngFor loop. The problem I am encountering is tha ...

The form features a "Select all" button alongside a series of checkboxes for multiple-choice options

I am facing difficulties trying to get the "Select all" and "Remove all" buttons to function properly within my form. Whenever I remove the "[]" (array) from the name attribute of the checkboxes, the JavaScript code works perfectly fine. However, since I n ...