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

Minimize or conceal iframe

This iframe contains a Google form that cannot be edited. I am looking for a way to close or hide this iframe, either through a button, a popup window button, or without any button at all. The $gLink variable holds the Google form link through a PHP sessio ...

Printing the elements of an array in a repetitive sequence

var arr = [a, b, c]; In this specific array setup, index 0 corresponds to "a", index 1 corresponds to "b", index 2 corresponds to "c". console.log(arr[0]) // will output > "a" console.log(arr[1]) // will output > "b" console.log(arr[2]) // will ...

What are some clever ways to outsmart bootstrap rows?

Trying to find a way to work around Bootstrap rows. I have multiple col-..-.. items that I need to fit into one row, but modifying 8 complex .js files is not an option for me - and they refer to the children of the div I used as a bootstrap row. HTML manip ...

Image not appearing when sharing on Facebook

I've been trying to create a Facebook share button using the Javascript SDK, and here is the code I have been utilizing: $(function() { $('.facebook-share').click(function(e) { e.preventDefault(); FB.ui({ method: 'feed& ...

Different CSS values can be applied for specific versions of Internet Explorer by using conditional comments

I am dealing with a CSS class named "myclass" that requires a z-index of 5 specifically for IE8. I have attempted to achieve this using the following methods: .myclass{ z-index: 5\9; } ---> Interestingly, this method applies from IE10 onwards a ...

What is the best way to trigger an AJAX request when a user navigates away from a webpage or closes the

The Challenge at Hand Greetings, I am currently developing a database-driven game that involves users answering questions and earning the right to change the question by providing the correct answer. However, I have encountered a significant issue which ...

How can I use AngularJS to filter ng-repeat values based on the input ng-model value of another field?

Can I Repeat Values Based on Another Input NG-Model Value in AngularJS? There is one input value, let's say Social Psychology, and the corresponding ng-model for this value is kpcategory. I am using ng-repeat="question in questions" to list all ...

Switching the way hyperlinks behave when clicked, from requiring a double-click to a single

My code is working properly, but I need my links to open with just a single click. The issue is that the delete, approve, and not approve links require a double click for their function to run. I'm hoping someone can help me with this. index.php < ...

Are you experiencing issues with modal contents extending beyond the modal on smaller screens?

I recently installed a modal plugin called blockUI for my image uploading needs. Although I have styled and positioned everything accordingly, I am facing an issue: Whenever I resize the browser screen, switch to my iPhone, or use another screen, some con ...

Convert HTML tables from Yahoo Pipes into an array of JSON objects

Currently, I am experimenting with Yahoo Pipes in an attempt to convert multiple tables within a DIV into an array of JSON objects. At the moment, the HTML is being successfully parsed. Here is my current setup on Yahoo Pipes I envision each table cell ...

Exploring the process of generating, monitoring, and initiating personalized events in ReactJS

To establish a global custom event for listening and triggering purposes, here is how it can be achieved using jQuery: $(document).on('myCustomEvent', function(){ console.log("myCustomEvent triggered"); }) $(document).trigger('myCustom ...

Using jQuery, we can replace all `<span>` elements with `<img>` elements and then verify if the images have been successfully loaded

Similar Inquiry: jQuery check if image is loaded I find myself in a scenario where the following HTML structure is utilized: <div class="image"> <img class="" src="content-images/1.jpg"> <span class="slide" rel="content-images/ ...

What is the best way to save a jQuery or JavaScript variable into a JSON file?

Is there a way to save a jquery variable in a json file? I have the following: var image='/test/test.png'; I am obtaining this path through file upload: <input type="file" name="imageurl" value="imagefile"></input> Therefore, I ne ...

To activate an underline on text, simply right-click and select "text

All the anchor tags on my website have been styled with text-decoration: none. Additionally, I have added a CSS rule based on a helpful answer: a, a:hover, a:active, a:visited { text-decoration:none; } However, whenever I right-click on a link on my ...

What is the process for converting the color names from Vuetify's material design into hexadecimal values within a Vue component?

I'm looking to obtain a Vuetify material design color in hexadecimal format for my Vue component's template. I want to use it in a way that allows me to dynamically apply the color as a border, like this: <div :style="`border: 5px solid $ ...

Error: The hook call is invalid and can only be made within the body of a function component in ReactJS

Hello everyone, I am currently facing an issue with saving the lat and lng variables in the state within a hook. When trying to do so, I encounter the following error message: "Error: Invalid hook call. Hooks can only be called inside the body of a functio ...

Having trouble getting the CSS Transform property to be affected by ScrollTop

Hello everyone, I am attempting to create a ball that has a 50% radius and rolls left based on the user's scroll movements. So far, I have successfully made it move left in relation to ScrollTop, but unfortunately, I cannot get the transform property ...

Creating a stylish gradient text color with Material-UI's <Typography /> component

Is there a way to apply a gradient font color to a <Typography /> component? I've attempted the following: const CustomColor = withStyles({ root: { fontColor: "-webkit-linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)", }, })(T ...

Eliminate forward slashes from the telephone number

I am trying to figure out how to format a USA phone number by removing slashes and brackets. I have searched on Google, but I cannot find the answer. I would like to use regex to achieve this, while keeping the plus sign at the start intact. For example, ...

Encountering issues with proper function of history.listen within React Router

I am struggling to get my function to work every time React detects a change in the URL. The history.listen method is not triggering (the console.log statement is not showing up). I have read that this issue may be related to using BrowserRouter, but when ...