Guide to: Implementing Radio Buttons to Adjust Image Opacity

How can I dynamically change the opacity of an image using JavaScript when a radio button is clicked?

I attempted to achieve this using a forEach function, but the current code causes all images to instantly switch to opacity 1;

Additionally, after refreshing the page, the radio button remains selected.

let img = document.querySelectorAll('.poll_img');
    let radio = document.querySelectorAll('.radio_button');

    radio.forEach(radioButton => {
        if (radioButton.checked === true){
            img.forEach(image => {
                image.style.opacity = 1;
            })
        }
    })
<form class="poll_form" action="">
  <div class="poll_bar">
    <img class="poll_img poll_img1" src="assets/images/poll_bar-icon.svg" alt="">
    <label class="radio_title" for="radio1">Atlantic Forest, South America
    </label><input class="radio_button" type="radio" name="group1" id="radio1">
    <div class="check"></div>
  </div>

  <div class="poll_bar">
    <img class="poll_img  poll_img2" src="assets/images/poll_bar-icon.svg" alt="">

    <label class="radio_title" for="radio2">Borneo Island, Southeast Asia
    </label><input class="radio_button" type="radio" name="group1" id="radio2">
    <div class="check"></div>
  </div>
</form>

Answer №1

Instead of simply styling the buttons with JS on initial load, it is better to set up event listeners that trigger functions when a radio button is selected.

It would be more efficient to target and adjust the opacity of only the corresponding image instead of looping through all the images every time.

radio.forEach(r => {
  r.addEventListener("click", () => {
    let relatedImg = r.parentNode.querySelector("img");
    relatedImg.style.opacity = 1;
  }
})

To ensure only the selected image remains fully opaque, you can implement a function within the event listener to reset the opacity of other images.

Edit: Here's a simple way to achieve this:

radio.forEach(r => {
  r.addEventListener("click", () => {
    let relatedImg = r.parentNode.querySelector("img");
    updateImages(relatedImg);
  }
})

function updateImages(changedImg) {
  img.forEach(image => {
    if (image === changedImg) {
      image.style.opacity = 1;
    } else {
      image.style.opacity = 0;
    }
  }
}

Answer №2

When working with JavaScript, remember that the single equal sign = is used for assignment, not comparison. To compare two values, you should use a double equal sign ==.

For example, in line 6 of your JS code, the condition should be written as:

if (checkbox.checked == true) {...

or simply as:

if (checkbox.checked)

Answer №3

        const radioButtons = document.querySelectorAll('.radio_button');

    radioButtons.forEach(button => {
        button.addEventListener("click", adjustOpacity);
    });

}

adjustOpacity = button => {
    const selectedButton = button.currentTarget;
    let targetImage = selectedButton.parentNode.querySelector('img');
    targetImage.style.opacity = 1;

    if(selectedButton.checked == false){
        targetImage.style.opacity = 0.4;
    }
}

Although the opacity changes correctly, once an option is chosen, the image does not return to original low opacity.

Answer №4

To make your radio input functional, you have two options:

1. First

You can encapsulate your JavaScript code within a function and then call this function in your HTML like so:

<form class="poll_form" action="">
    <div class="poll_bar">
      <img class="poll_img poll_img1" src="picture.png" alt="">
      <label class="radio_title" for="radio1">Atlantic Forest, South America
      </label><input onchange="lightUpPic()" class="radio_button" type="radio" name="group1" id="radio1">
      <div class="check"></div>
    </div>

    <div class="poll_bar">
      <img class="poll_img  poll_img2" src="picture.png" alt="">

      <label class="radio_title" for="radio2">Borneo Island, Southeast Asia
      </label><input onchange="lightUpPic()" class="radio_button" type="radio" name="group1" id="radio2">
      <div class="check"></div>
    </div>
  </form>

In your JavaScript file:

function lightUpPic(){
let img = document.querySelectorAll('.poll_img');
    let radio = document.querySelectorAll('.radio_button');
    radio.forEach(radioButton => {
        if (radioButton.checked == true){
            img.forEach(image => {
                image.style.opacity = 1;
            })
        }
    })
}

2. Second

Alternatively, you can add an Event Listener to each of your radio inputs to trigger the desired JavaScript function upon clicking.

Answer №5

After finally finding the solution, credit goes to Miles Grover for helping me figure it out.

{
const start = () => {

    let radiobuttons = document.querySelectorAll('.radio_button');

    radiobuttons.forEach(rb => {
        rb.addEventListener("change", adjustOpacity);
    });
}

adjustOpacity = rb => {
    const radioBtn = rb.currentTarget;
    let relatedImage = radioBtn.parentNode.querySelector('img');
    relatedImage.style.opacity = 1;

    resetOpacity();
}

const resetOpacity = () => {
    let radiobuttons = document.querySelectorAll('.radio_button');
    radiobuttons.forEach(rb => {
        if(rb.checked == false){
            let img = rb.parentNode.querySelector('img');
            img.style.opacity = 0.1;
        }
    })
}

start();

}

Answer №6

Here's a neat trick to achieve the following:

  • When the page loads, all pictures have an opacity of 0.3
  • Upon selecting radio button 1, picture 1's opacity becomes 1 while the rest stay at 0.3
  • Similarly, selecting radio button 2 changes picture 2's opacity to 1 and the others to 0.3... and so on

HTML:

<form class="poll_form" action="">
    <div class="poll_bar">
      <img class="poll_img  poll_img1" src="picture.png" alt="">
      <label class="radio_title" for="radio1">Atlantic Forest, South America
      </label><input onchange="lightUpPic(event)" class="radio_button" type="radio" name="group1" id="radio1">
      <div class="check"></div>
    </div>

    <div class="poll_bar">
      <img class="poll_img  poll_img2" src="picture.png" alt="">

      <label class="radio_title" for="radio2">Borneo Island, Southeast Asia
      </label><input onchange="lightUpPic(event)" class="radio_button" type="radio" name="group1" id="radio2">
      <div class="check"></div>
    </div>
  </form>

JS:

    let allImages = document.querySelectorAll('.poll_img');
allImages.forEach(i=> i.style.opacity=0.3);

function lightUpPic(evt){
    let imageNumber = evt.target.id.replace( /^\D+/g, '');
    let imgAssigned = document.querySelectorAll('.poll_img' + imageNumber);

    let radio = document.querySelectorAll('.radio_button');
    radio.forEach(radioButton => {
        if (radioButton.checked == true){
            allImages.forEach(image => {
                image.style.opacity = 0.3;
            })
            imgAssigned[0].style.opacity=1;

        }
    })
}

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

Tips for addressing Navbar collision with body content or other pages using CSS

I have successfully created a navigation bar using CSS and JS. The image below illustrates the example of my navigation bar: https://i.sstatic.net/2l4gj.png The issue I am facing is that when I select "MY ACCOUNT," it displays some content. However, upon ...

Tips for organizing three flexbox divs in a horizontal row

Within the content div, I have three separate divs that resize when the browser window is adjusted. The blue and red divs should maintain a fixed width The green div should resize to fill any available space on the left I attempted to accomplish this usi ...

Whenever a query is entered, each letter creates a new individual page. What measures can be taken to avoid this?

Currently, I am working on a project that involves creating a search engine. However, I have encountered an issue where each time a user types a query, a new page is generated for every alphabet entered. For instance, typing 'fos' generates 3 pag ...

The website is having trouble reading the local json file accurately

Currently, I have developed an HTML site that utilizes JavaScript/jQuery to read a .json file and PHP to write to it. In addition, there is a C++ backend which also reads and writes to the same .json file. My goal is to transmit the selected button informa ...

I recently realized that my website has a strong Björk influence when viewed in IE. Any suggestions for what I should do next

After using Chrome and Firefox for a while, I decided to test out my website on IE8. To my surprise, the results were disastrous. The navigation was impossible, rotations were not rendering correctly, and everything looked like a complete mess. Do any of ...

Is it possible to implement Ajax functionality in JavaScript without using XMLhttp and connection the same socket for every request?

Can data on a page be communicated and updated without the need for reloading, all while avoiding the XMLHttpRequest object and using the same connection or socket for each request (without closing the connection each time)? ...

Steps for choosing an image and embedding it within a div element

Upon loading the site, an image is displayed with the following code: <img id="some_Image" src="some_source"> However, I am looking to avoid requesting this image again from "some_source". This is because calculating the image can be resource-inten ...

Display HTML in JavaScript without altering the Document Object Model

Is it possible to style a custom HTML tag called "location" without directly modifying the DOM? For instance, having <location loc-id="14" address="blah" zipcode="14" /> Would it be feasible to render it like this: <div class="location"> ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

A quick and easy way to locate the object tag along with the param, and insert the embed tag within an HTML document is

Struggling with understanding the simple HTML DOM of PHP? You're not alone. As a newcomer to the programming industry, following instructions can be challenging. I've been searching for how to locate the object tag and embed, but haven't fou ...

Guide for integrating the shadcn/ui Range Date Picker within a Form

Encountering an issue with using The Range Date Picker within the Form component. Specifically, I am looking to store {from, to} values of the range in an object, however, utilizing an object as a Form field value results in error messages not functioning ...

How can I turn off the animation for a q-select (quasar select input)?

I'm just starting out with Quasar and I'm looking to keep the animation/class change of a q-select (Quasar input select) disabled. Essentially, I want the text to remain static like in this image: https://i.stack.imgur.com/d5O5s.png, instead of c ...

Tips for turning on a gaming controller before using it

Current Situation In my ionic side menu app, I have a main controller called 'main view'. Each tab in the app has its own controller, which is a child of the main controller. The issue I'm facing is that when I start the app, the first cont ...

Determine whether the elements within an array are present on the webpage. If they are, display an alert. If not, reload the page

Initially, I had a userscript designed to search for a specific string within a webpage. If the script failed to locate the string, it would refresh the page after 4 seconds: var item = 'apple'; if(document.body.innerHTML.toString().indexOf(item ...

Overlapping Divs and Colliding Elements

I am currently exploring the moment when my two yellow divs will overlap and make contact with each other. It seems that the collision detection is triggering true even when the divs are not intersecting. If you'd like to take a look at the example, ...

Acquire Formik Validation for the Current Year and Beyond

How can I ensure that the input in Formik is restricted to the currentYear and later years only? const currentYear = new Date().getFullYear(); expiryYear: yup .string() .required('Please select an expiry year') .min(4, `Year format must be grea ...

Using Leaflet JS to implement multiple waypoints on a map

I am trying to create a route with multiple waypoints without hardcoding any data. My waypoints array should dynamically include latitude and longitude values. How can I achieve this? var data = [ { "title": 'Chennai', " ...

What is the best way to extract URL query parameters and store them in a MySQL database using Node.js and Express

I am working on a project where I need to store specific information like names and widths from the URL query into my MySQL database. The format of the URL query should resemble this: /register?name=XXXX&width=###.### However, I seem to be facing ch ...

What causes the 'find' query to return a Query object instead of the expected data in MongoDB?

After researching extensively on SO, I have yet to find a solution to my ongoing issue. Currently, I am in the process of developing a project using node, express, and mongodb. To start off, I created a seeder file to populate some data into mongodb: var ...

The appearance of CSS can vary depending on the screen resolutions in which it is

I am encountering an issue with my HTML component that utilizes a booking engine. The parent width of the component is set, and the children elements inherit this width. There are three input fields and a search button within the component. The problem ari ...