What is the reason radio:checked is not properly changing the color of the div?

Having issues with my circle divs not changing to a black background when the linked radios are checked. This is for a carousel that cycles automatically in JavaScript. Manually changing the color works fine, but the CSS doesn't seem to apply. Help, please!

Here is the CSS:

#radio1:checked ~ .navigation-auto .auto-btn1{
    background: black;
}
#radio2:checked ~ .navigation-auto .auto-btn2{
    background: black;
}
#radio3:checked ~ .navigation-auto .auto-btn3{
    background: black;
}
#radio4:checked ~ .navigation-auto .auto-btn4{
    background: black;
}
#radio5:checked ~ .navigation-auto .auto-btn5{
    background: black;
}

The HTML section that matters:

           <div class="slides">
                <input type="radio" name="radio-btn" id="radio1">
                <input type="radio" name="radio-btn" id="radio2">
                <input type="radio" name="radio-btn" id="radio3">
                <input type="radio" name="radio-btn" id="radio4">
                <input type="radio" name="radio-btn" id="radio5">
          .....rest of code

And for the navigation:

        <div class="navigation-auto">
                <div class="auto-btn1"></div>
                <div class="auto-btn2"></div>
                <div class="auto-btn3"></div>
                <div class="auto-btn4"></div>
                <div class="auto-btn5"></div>
        </div>

Not sure if this is enough information, let me know if you need more. Manually changing the div color works, but the radio:checked functionality doesn't seem to be working for me.

Here is the JavaScript:

var counter = 1;
setInterval(function(){
    document.getElementById('radio' + counter).checked = true;
    counter++;
    if(counter >5){
        counter =1;
    }
}, 5000);

Answer №1

To ensure proper functionality, the radio buttons should be positioned above the .navigation-auto element and share the same parent:

#radio1:checked ~ .navigation-auto .auto-btn1{
    background: black;
}
#radio2:checked ~ .navigation-auto .auto-btn2{
    background: black;
}
#radio3:checked ~ .navigation-auto .auto-btn3{
    background: black;
}
#radio4:checked ~ .navigation-auto .auto-btn4{
    background: black;
}
#radio5:checked ~ .navigation-auto .auto-btn5{
    background: black;
}

.navigation-auto > div
{
  width: 1em;
  height: 1em;
  display: inline-block;
  border: 1px solid red;
}
           <div class="slides">
                <input type="radio" name="radio-btn" id="radio1">
                <input type="radio" name="radio-btn" id="radio2">
                <input type="radio" name="radio-btn" id="radio3">
                <input type="radio" name="radio-btn" id="radio4">
                <input type="radio" name="radio-btn" id="radio5">

                <div class="navigation-auto">
                        <div class="auto-btn1"></div>
                        <div class="auto-btn2"></div>
                        <div class="auto-btn3"></div>
                        <div class="auto-btn4"></div>
                        <div class="auto-btn5"></div>
                </div>
           </div>

If this arrangement is not feasible, utilizing JavaScript is necessary:

for(let i = 0, nav = document.querySelector(".navigation-auto"), slides = document.querySelectorAll('.slides > input[name="radio-btn"]'); i < slides.length; i++)
{
  slides[i].addEventListener("click", e =>
  {
    for(let n = 0; n < nav.children.length; n++)
    {
      nav.children[n].classList.toggle("checked", n == i);
    }
  });
}
.navigation-auto > div.checked
{
  background-color: black;
}
.navigation-auto > div
{
  width: 1em;
  height: 1em;
  display: inline-block;
  border: 1px solid red;
}
      <div class="navigation-auto">
              <div class="auto-btn1"></div>
              <div class="auto-btn2"></div>
              <div class="auto-btn3"></div>
              <div class="auto-btn4"></div>
              <div class="auto-btn5"></div>
      </div>
           <div class="slides">
                <input type="radio" name="radio-btn" id="radio1">
                <input type="radio" name="radio-btn" id="radio2">
                <input type="radio" name="radio-btn" id="radio3">
                <input type="radio" name="radio-btn" id="radio4">
                <input type="radio" name="radio-btn" id="radio5">
           </div>

Answer №2

It seems like your current approach may not yield the desired results. One way to make it work is to encapsulate each radio input and its corresponding div content inside a container to prevent unintended effects on other elements.

Consider structuring your code like this:

input[type="radio"]:checked ~ div {
  color: red;
}
<div>
    <input type="radio" />
    <div>content</div>
</div>

<div>
    <input type="radio" />

    <p>paragraph</p>
    <div>content</div>
</div>

For a live example, you can check out this link: https://codesandbox.io/s/wizardly-bhaskara-nln6gr?file=/src/styles.css:36-89

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

I am encountering an issue while developing a JavaScript filtering system

Hey everyone, I need help with coding a filter in JavaScript and I'm running into an error (Uncaught TypeError: todos.forEach is not a function) that I can't figure out. Can someone assist me in resolving this issue? const todoFilter = docume ...

Check to see if a div element with an id that contains a numerical value has been

My HTML code contains X elements, each with an ID in the format: viewer_mX In this case, X is a number ranging from 1 to m (where m varies). I am looking to utilize JavaScript to retrieve the respective element's number X when a user clicks on one ...

Is there a way to create a smooth transition for a background image, starting from grayscale and gradually transitioning to

I have a Bootstrap website featuring a colored background image. I am looking to achieve a specific effect where the image begins in grayscale and slowly transitions into color as the page loads, without requiring any user interaction. How can I accomplis ...

Fuzzy backdrop with razor-sharp edges

In the process of designing a website, I am in need of a header with a blurred background that retains sharp edges. To achieve this effect, I implemented the use of ::before in my CSS code. Current Outcome: (For full clarity, it may be necessary to view ...

What is the best way to ensure that Bootstrap columns are spacious enough to fit advertisements?

Using Bootstrap 5, I have created a page layout with 3 columns: <div class="container"> <div class="row"> <div class="col-md-3">LEFT</div> <div class="col-md-6">CENTER</div& ...

Image positioned at the top with text links situated at the bottom thanks to Flexbox

I am working on a project that involves placing a flex menu on top of a picture slider. I am struggling to align the items on the same baseline while keeping them on the same line. a img{ height: 40px; } .links{ display: flex; align-items: baselin ...

What is the best way to center a form element and an image link vertically within a div?

I'm having trouble aligning a search form and an image link within a div. I've attempted using 'display:inline', which did place them on the same line, but not in the way I wanted. I also experimented with adjusting width, float, and pa ...

Pictures squeezed between the paragraphs - Text takes center stage while images stand side by side

I'm struggling to figure out how to bring the text between the two images to the front without separating them. The images should be positioned next to each other with a negative square in-between, and the text within this square should be centered b ...

Adjust the height seamlessly on the homepage without the need for scrolling, while maintaining a stationary navigation bar and footer

Our latest project is designed specifically for mobile use. The fixed navigation bar is functioning perfectly. We also have a fixed footer with icons at the bottom. (All working well) The challenge we are facing is to make the content between the naviga ...

What is the best way to display Bootstrap dynamic tabs in a single row without them overflowing and requiring a scroll button to access all the tabs

Is there a way to dynamically display Bootstrap tabs? I want the content in the tab to show when the link is clicked, and also have a close button. I need the tabs to be aligned in a single row without wrapping down if they don't fit. Here's an ...

Ways to troubleshoot an issue that arises when the `onChange` event is not utilized in a radio button component on a

When using this component for radio buttons without the Onchange function, I sometimes encounter the following error on the page related to onUpdate: TypeError: this.props.onUpdate is not a function onChange(e) { let value = e.target.value; this ...

Is there a way to position the primefaces DefaultMenuModel in front of an accordion panel?

Currently, I have a DefaultMenuModel nested within a tab in an accordion panel. However, the menu is appearing behind the tab of the accordion panel and I want to adjust the z-index of the menu so that it appears in front of the tab. Here is the current ...

What is the method for accessing font sizes through CSS code?

Why is the font size value in CSS returning incorrect values? Check out this jsFiddle example Here's the HTML code snippet: <div id="test">TEXT</div> <div id="test2">TEXT2</div> Now, take a look at the CSS: #test{ font ...

What is the best way to draw a rectangle outline in Vue.js without the need for any additional packages?

I have been attempting to craft a rectangle outline using vueJS, but so far I have not had much success. I am hoping to achieve this using only CSS, but despite my efforts, I have not been able to find a solution. My goal is to create something similar to ...

Achieve full height of parent with rotated text

Hey, I've been experimenting with some CSS transforms and I'm having trouble getting this to work properly. Check it out here I'm using Bootstrap 4 to create two columns; an image on the left and text on the right. I want the text to be ce ...

assigning the browser's width to a variable within an scss file

Is there a way to dynamically set the browser's width as a variable? I am familiar with @media queries, but I need to calculate the browser's width for a specific purpose. I attempted using jQuery to achieve this, and it works well with a fixed ...

"Displaying <canvas> at its true resolution even when zoomed in, thanks to Retina technology

I am currently working with a <canvas> element to create vector graphics and I want to ensure that it displays in the highest quality possible while using minimal resources across various viewing conditions. Specifically, I aim to achieve a 1:1 mappi ...

The text inside a paragraph tag is causing other elements to shift when the window size is changed

With three divs displayed inline, each containing an image, heading, paragraph, and anchor tags, a design issue arises. The inconsistency in text lengths under the images causes visual discrepancies when resizing the window. For example, while the first tw ...

HTML is not connecting to CSS

I'm having trouble linking my external CSS to my HTML file. In the head of my index.html, I have this code: <head> <title>Twenty by HTML5 UP</title> <meta charset="utf-8" /> <meta name="viewport ...

What is the process for including CSS in the .ashx.cs code-behind file in ASP.NET?

How can I insert a css class in the .ashx file while the .aspx UI page displays it as a string? What is the method to include css in the code behind of the .ashx page? I would like the text "Cook" to be displayed in red. Problem: https://i.sstatic.net ...