Modify a CSS attribute by toggling a checkbox

Currently, I am working on implementing a hamburger menu for my website. My aim is to darken the rest of the page when the hamburger menu is clicked.

In order to achieve this effect, I have added a div with the following code:

<div id="black"></div>

This is how I have structured my HTML:

<nav role="navigation">
    <div id="menuToggle">
      <input type="checkbox" id="mycheckbox"/>
      <span></span>
      <span></span>
      <span></span>
      <?php
        wp_nav_menu(
          array(
            'theme_location' => 'top_menu',
            'container' => 'ul', //to prevent having a surrounding div
            'menu_class' => 'site__header__menu', //my custom class
          )
        );
      ?>
    </div>
  </nav>
  <div id="black"></div>

Currently, the display property for this div is set to none. I want it to switch to inline/block when the hamburger menu is clicked.

I attempted to accomplish this using JavaScript:

function functionTest() {
const cb = document.querySelector('#mycheckbox');
const black = document.querySelector('#black');
  if (cb.checked) {
    black.style["display"] = "inline";
  } else {
    black.style["display"] = "none";
  }
}

Unfortunately, this solution did not work as expected. Your help would be greatly appreciated. Thank you in advance.

Answer №1

To implement this effect without using any JavaScript, you can utilize pure CSS along with the tilde selector.

#mycheckbox:checked ~ div #black {
   display:block;
}

body {background:#fff;}
#black {
  background: #ccc;
  display:none; padding:20px; position:absolute; left:0;right:0;top:30px;bottom:0;}

.opened-menu #black {display:block;}
.item,
.menu {
  display:inline-block;
  min-width:100px;
  font-size:14px;
  border:1px solid;
  padding:10px;
  text-align:center;
}

#mycheckbox:checked ~ div #black {
  display:block;
}
<input type="checkbox" id="mycheckbox"/>
<label for="mycheckbox">
Menu
</label>
<div>


<div id="black">  
  <a href="#" class="item">Item</a>  
  <a href="#" class="item">Item</a>  
  <a href="#" class=" menu">Menu</a>
</div>


</div>

Answer №2

Big shoutout to everyone who contributed their knowledge and expertise. I recently made a modification to this code snippet:

<input type="checkbox" id="mycheckbox" onclick="functionTest()"/>

After receiving advice from Jan Pfeifer, who pointed out that there was no event handler attached to anything, I was able to resolve the issue successfully!

Answer №3

To achieve this using only CSS, you can follow the steps below. Please note that this method may not work on Firefox or older browsers. Check the compatibility here.

#black {
    display: none;
}

nav:has(cb:checked) + #black {
    display: inline;
}

See it in action here: https://jsfiddle.net/6vwmy95L/22/

If you prefer, you can also utilize an event listener;

const checkbox = document.querySelector("#mycheckbox");
const black = document.querySelector('#black');

if (checkbox) {
  checkbox.addEventListener("change", (event) => {
    if (event.currentTarget.checked && black) {
      black.style.display = "inline";
    } else {
      black.style.display = "none";
    }
  });
}

As mentioned by @somethinghere, consider restructuring your HTML for better browser support if possible.

If altering the HTML structure is not an option and older browser compatibility is required, use the JavaScript approach.

In case changing the HTML is not feasible and support for older browsers is essential, opt for the :has method in CSS.

If ensuring functionality with disabled JavaScript and older browsers is a priority, revise the HTML layout based on @Marin HTML's suggestion.

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 removeClass method does not affect the class attribute when using $(this).attr('class'), but only when using $(this).attr('id')

I am currently facing an issue with reducing the size of my jQuery code. The main function is to validate a form - if empty, I want to add a class of 'highlight' or remove it using addClass('highlight') and removeClass('highlight&a ...

Using Async/Await for Timers within a Loop in Javascript

Currently developing a "Timeblocks" style application for university. The main concept involves having a list of subtasks, each with a specified time limit. The goal is to iterate through these tasks, utilizing a timer to countdown the allocated time and t ...

Executing a function only on one click

Recently diving into the world of JavaScript, I attempted to create a button that would log "hey" in the console upon being clicked. However, I encountered an issue where it logs "hey" before clicking the button and then does nothing when the button is act ...

Creating a border with a unique and specific image

Is there a way to use an image as the border for my div elements? The key requirement is that the border must be positioned outside the box without affecting its size. It's important to note that all div items have the same width, but varying heights ...

Bundle the modules while maintaining global scope for all variables

To simplify my code for a specific problem, let's consider the following setup: In module1.js, I have the following class: export class MyClass { }; And in index.js, I import MyClass from module1.js and assign it to a variable: import { MyClass } fro ...

Using JSON strings in an HTML data attribute isn't functioning as expected

I am working with checkboxes that have a data attribute called data-route. However, when hovering over them and trying to alert the values, I only get one letter or symbol. Here is my code snippet: foreach ($this->coords as $index=>$val ...

Unable to retrieve all URLs with getDownloadURL

Having an issue with my firebase storage upload - I am uploading three photos, but when I try to retrieve the firebase URL for each image using getDownloadURL, it only returns two objects instead of three. //const uploadedFilesURL = []; upl ...

"Error: Unable to locate CSS background image file: net::ERR_FILE_NOT_FOUND

I currently have a background image set for the bottom of the header as shown below: header { background:url(../img/header_bg.png) #ea6225 no-repeat; background-size: 100% auto; background-position:left bottom; } The images are located in a folder ...

Experiencing difficulty in transferring array information from a parent component to a child component within an

I'm currently working on a task where I need to pass data from a parent component to a child component. The data consists of an array that is nested within another array. parent.component.html <div *ngFor="let parent of parentArray; index as ...

the box is having trouble with its animation

This issue revolves around the use of CSS3 properties like -webkit-keyframes and -webkit-box-align. To learn more about this problem, please check out http://codepen.io/pleasureswx123/pen/fljFH /* sample css code */ <style> .box { di ...

Send the user back to the previous page once authentication is complete

I am integrating Google authentication through Passport in my web application and I am facing an issue with redirecting the user back to the original page they requested after a successful sign-in. It seems like the use of location.reload() might be causin ...

Is there a way to verify if a checkbox has been checked?

Having trouble with this code: if($('#primayins').prop('checked')) { $("#tx_nm0x0_pricingplan").val(1); } else { $("#tx_nm0x0_pricingplan").val(2); } It keeps returning false consistently ...

What is the best way to utilize a while loop in order to calculate the Fibonacci sequence?

Just recently delved into the world of Js and encountered an issue that has me stumped. Despite exhaustive searching, I haven't been able to find a similar solution. Any assistance would be greatly appreciated. var i = 0; var j = 1; var k = 0; fun ...

Stop the promise chain when the first error callback is encountered

Here is a sequence of promises I am dealing with: Transaction.findPublic({}).then(function(transactions) { combined = combined.concat(transactions); return JoinEvent.find().exec(); }, function(err) { return res.status(503).send(er ...

"Material-UI enhanced React date picker for a modern and user-friendly

Currently, I am utilizing the Date picker feature from Material UI. The code snippet responsible for implementing it is as follows: import { DatePicker } from 'redux-form-material-ui'; <Field name="birthDate" ...

Steps to create full screen jQuery tabs with overflow scroll feature in the content

I am in the process of creating a responsive web design using jQuery tabs. My goal is to make one page of the website occupy the entire screen (100% height and width), have a fixed height for the div.ui-tabs-nav, and enable scrolling for the content of div ...

Tips for obtaining images and displaying them using Node.js

Trying to obtain an image and display it on a URL using the request module. For instance, aiming to fetch the image https://www.google.com/images/srpr/logo11w.png, and show it on my URL http://example.com/google/logo. Alternatively, displaying it with &l ...

A React component created in a class cannot effectively update its state when using a functional component to pass

I'm currently working on a React project that involves both a Class component and a Functional Component. In my Class component, I have a function that updates the name in its state. The issue arises when I try to pass this function as a property to t ...

Having trouble transferring data from AppComponent to a function

When I send the email data to this.user in the constructor, it gets stored in AppComponent. Next, I need this variable in the function getUserData to import some data...but the console.log shows undefined, and there is also an error for users: Cannot read ...

How to hide the header on a specific page using Angular

Currently, I am working on an Angular project and my requirement is to hide the header block specifically on the login page. Despite attempting to hide the header on the login page, it seems that my efforts have been unsuccessful so far. Is there anyone wh ...