Deselect a checkbox by selecting a radio button with just Javascript code

Hey there! I'm currently delving into the world of pure JavaScript and could really use some guidance on a particular issue.

Here's what I'm aiming to accomplish:

I'd like to design a checkbox that triggers the opening of a window when clicked. Inside this window, there will be several radio buttons. If a user selects one of these radio buttons, the checkbox outside the window should automatically uncheck, causing the window to close.

Challenges Faced:

  • The reversal function in the code isn't functioning correctly.

  • The linkage between checking a radio button and unchecking the checkbox seems to be broken.

Code Snippet:

let box = document.querySelector('.dd_box')

let ddCb = document.querySelector('#dd_cb')
let ddRb = document.querySelector('.dd_rb')

// Normal operation
ddCb.addEventListener('change', () => {
  box.classList.add('active')
})

// Reverse functionality
ddRb.addEventListener('click', () => {
  box.style.opacity = 0; // Avoid displaying the initial style when toggling the 'active' class

  box.classList.add('in-active');
  box.classList.remove('active');

  // Forcing DOM update
  setTimeout(() => {
    box.classList.add('active');
    box.style.opacity = '';
  }, 5);

  box.addEventListener('animationend', onAnimationEnd);
})

function onAnimationEnd() {
  box.classList.remove('active', 'in-active');
  box.removeEventListener('animationend', onAnimationEnd);
}
body {
  background-color: rgba(30, 30, 30);
}

#dropdown {
  width: 500px;
  height: 300px;
  top: 50px;
  left: 100px;
  position: absolute;
}

#dropdown input[type=checkbox] {
  display: none;
}

.dd_bttn
/* Clickable button */

{
  width: 25px;
  height: 25px;
  top: 0px;
  left: -25px;
  position: absolute;
  z-index: 10;
  background-color: darkorange;
  cursor: pointer;
}

.dd_bttn:hover {
  background-color: purple;
}

.dd_box {
  width: 100%;
  height: 100%;
  top: 0px;
  left: 50%;
  position: absolute;
  transform: scale(0);
  background: grey;
}

@keyframes zzzib {
  0% {
    transform: translate(-50%) scale(0);
    background-color: red;
  }
  20% {
    transform: translateX(-50%) scale(0.9);
  }
  100% {
    transform: translateX(-50%) scale(1);
  }
}

.dd_box.active {
  animation: zzzib 1s forwards;
  animation-timing-function: ease-in-out;
}

.dd_box.in-active {
  animation-direction: reverse;
  animation-timing-function: ease-in-out;
}
<div id="dropdown">
  <input type="checkbox" id="dd_cb">
  <label id="dd_label" for="dd_cb">
          <div class="dd_bttn"></div>
        </label>
  <div class="dd_box">
    <input type="radio" class="dd_rb" name="rb">
    <input type="radio" class="dd_rb" name="rb">
    <input type="radio" class="dd_rb" name="rb">
  </div>
</div>

Answer №1

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    let box = document.querySelector('.dd_box')

    let ddCb = document.querySelector('#dd_cb')
   
    var inputs = document.querySelectorAll("input[type=radio]"),
  x = inputs.length;
while (x--)
  inputs[x].addEventListener("change", function() {

    alert('click');
    box.style.opacity = 0 // avoid showing the init style while switching the 'active' class

    box.classList.add('in-active')
    box.classList.remove('active')

    // force dom update
    setTimeout(() => {
      box.classList.add('active')
      box.style.opacity = ''
    }, 5)

    box.addEventListener('animationend', onanimationend)
  }, 0);
    // 
    ddCb.addEventListener('change', () => {
      box.classList.add('active')
    })


    function onanimationend() {
      box.classList.remove('active', 'in-active')
      box.removeEventListener('animationend', onanimationend)
    }
    body {
      background-color: rgba(30, 30, 30);
    }

    #dropdown {
      width: 500px;
      height: 300px;
      top: 50px;
      left: 100px;
      position: absolute;
    }

    #dropdown input[type=checkbox] {
      display: none;
    }

    .dd_bttn
    /*clickable button*/

    {
      width: 25px;
      height: 25px;
      top: 0px;
      left: -25px;
      position: absolute;
      z-index: 10;
      background-color: darkorange;
      cursor: pointer;
    }

    .dd_bttn:hover {
      background-color: purple;
    }

    .dd_box {
      width: 100%;
      height: 100%;
      top: 0px;
      left: 50%;
      position: absolute;
      transform: scale(0);
      background: grey;
    }

    @keyframes zzzib {
      0% {
        transform: translate(-50%) scale(0);
        background-color: red;
      }
      20% {
        transform: translateX(-50%) scale(0.9);
      }
      100% {
        transform: translateX(-50%) scale(1);
      }
    }

    .dd_box.active {
      animation: zzzib 1s forwards;
      animation-timing-function: ease-in-out;
    }

    .dd_box.in-active {
      animation-direction: reverse;
      animation-timing-function: ease-in-out;
    }
    <div id="dropdown">
      <input type="checkbox" id="dd_cb">
      <label id="dd_label" for="dd_cb">
              <div class="dd_bttn"></div>
            </label>
      <div class="dd_box">
        <input type="radio" class="dd_rb" name="rb">
        <input type="radio" class="dd_rb" name="rb">
        <input type="radio" class="dd_rb" name="rb">
      </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

Utilizing JSON for the setAttribute() method

While I've made progress on this issue, I've encountered numerous confusing methods. The goal is to utilize the key:value pairs in attr{} for the setAttribute() function without relying on any framework. If anyone could provide a straightforward ...

Creating a form in PHP with the power of JavaScript, AJAX, and jQuery

I have successfully created a registration form using HTML, processed the data with PHP, and utilized javascript, ajax, and jquery. However, I am facing an issue where I want to display a notification stating whether the operation was "inserted/failed" on ...

Could routerLinkActive be used to substitute a class rather than simply appending one?

I have a navigation bar icon that links to an admin route. I want this icon to change its appearance when on that specific route. To achieve this, I can simply replace the mdi-settings-outline class with mdi-settings, displaying a filled version of the sam ...

Console.log() will not display any JSON duplicates

My JSON data structure is pretty flat and can have duplicate attributes. I built a logic to remove the duplicates but when testing it out, something strange happened. The logic was always counting the attributes once, resulting in no duplicates. To test th ...

Creating two divs with equal heights in React using Material-UI at 50% each

I am currently utilizing a Material UI template within a react JS project. My goal is to create a div (or Grid in MUI) that spans 100% of its container's height, containing two nested divs (or Grids) that are each set at 50% height. If the internal c ...

Unexpected Error with Background Position Variable

Hello, I am attempting to create an animated background effect that moves up and down using the .animate() and .hover() methods in jQuery. Within my DOM, there is a div with id="#menu" containing a UL list where each item has a background positioned at dif ...

php - assign image to picture through file location

My webpage features an img element with the following code: <img id=".."class=".." src="setPhoto/second_photo.php"> In the source attribute, I have linked to a .php file: <?php $id = $_SESSION['u_id']; $sql = "SELECT * FROM users WHER ...

What is preventing my CSS Animation from activating on my website?

Is there something in the code preventing the animation from working properly? .projectLinks a{ background-color: var(--secondary-color); color: var(--main-color); padding: 2px 4px 4px 4px; border-radius: 15px; margin-right: 25px; text-decorati ...

Footer not adhering to the bottom of specific pages

I have been using the code snippet below to ensure that most of my pages stick to the bottom. However, I've noticed that the ones that don't are sub-menu items that contain a contact form with captcha. I'm not sure what's causing this i ...

Adding and adjusting the size of different DIV elements within a shared area

Looking to create a dynamic bar with the ability to add multiple child DIVs (similar to this: https://i.stack.imgur.com/tdWsq.jpg). Utilizing jQuery, jQuery UI, Bootstrap, and various plugins. The structure for the div (or span) system could be structured ...

What is the best way to retrieve the "name" and "ObjectId" properties from this array of objects? (Using Mongoose and MongoDB)

When trying to access the name property, I encountered an issue where it returned undefined: Category.find() .select("-_id") .select("-__v") .then((categories) => { let creator = req.userId; console.log(categories.name) //unde ...

The concept of undefined functions and the use of dependency injection may not always align

Recently starting with AngularJs, I am honing my skills by developing a single page Todo Application. However, I have encountered an issue while trying to load a localStorage factory that I intend to use for this project. Currently, I am stuck on the error ...

Insert text within a span tag next to a picture

Greetings everyone, Here is the current structure I am working on: <div class="payment-option clearfix"> <span class="custom-radio pull-xs-left">...</span> <label style="display:inline;width:100%"> <span style="fl ...

In search of a React.js/Redux OpenID library or example, particularly focused on Steam OpenID integration

Currently, I am developing a Node/Express REST + React/Redux application that requires Steam OpenID for authentication. Despite searching extensively for tutorials, libraries, or example code related to Steam OpenID (or any other OpenID), I have come up em ...

Leveraging ajax data to enhance visual representation in graphs

Having trouble fetching data from a database to display it in a graph.js graph. I've attempted setting a timeout for the async callback from Ajax, but nothing seems to be working. Any suggestions on how to make this work would be greatly appreciated! ...

What is the best method for extracting data from a node?

Issue: Upon sending a get request to node using the fetch API, an error is encountered. Refer to comment in code for details server.js const express = require('express'); const app = express(); const bodyParser = require('body-parser&apo ...

Axios and Postman generate unique X-CSRF tokens

Why does the X-CSRF token I receive from my axios request differ from the one I get in Postman? Here is how I am retrieving it: headers: { "X-CSRF-Token": "FETCH" } Furthermore, I am unable to use the X-CSRF token from my axios request in Postman as it ...

The onSubmit event handler seems to be malfunctioning within a Reactjs form

I recently started using React and encountered an issue with my form: class CustomForm extends React.Component { handleFormSubmit = (e) => { e.preventDefault(); const title = e.target.elements.title.value; const content = e ...

Tips for distinguishing between elements in React

I am facing an issue with zooming images on mouse hover using CSS. I have a code snippet that works well, but it zooms both images simultaneously. How can I differentiate between mouse movements over different elements in ReactJS? Here is the code: .styl ...

Can the <br> tag affect the layout in terms of horizontal space?

I am perplexed by the fact that it displays two lines vertically separated with a br tag differently than two lines vertically separated with the first line acting as a block level tag. For example, see this code snippet: https://jsfiddle.net/qzgeassf/ ...