Adjusting the transparency of numerous elements using JavaScript or jQuery

My task involves creating a large form where elements initially have an opacity of 0.5, and when a button is clicked, the opacity changes to 1.0. While I can achieve this using JavaScript, I want to find a more efficient way by avoiding individual if statements for each element. Additionally, some elements may need to toggle the opacity of multiple other elements.

Demo that needs revising

SIMPLE CSS

 [id^="dp"] {
    opacity: 0.5;
}

HTML

GROUP 1<BR>
    <input type="radio" id="abc1" name="abc1"  onclick="showabc();"/>
    <label for="abc1"> Yes </label>
    <input type="radio" id="abc2" name="abc1"  onclick="showabc();"/>
    <label for="abc2"> No </label>
    <div id="dpabc1">
    <H4>Content 1 is dimmed</H4>
    </div>

    GROUP 2<BR>
    <input type="radio" id="abc3" name="abc2"  onclick="showabc();"/>
    <label for="abc3"> Yes </label>
    <input type="radio" id="abc4" name="abc2"  onclick="showabc();"/>
    <label for="abc4"> No </label>
    <div id="dpabc7">
    <H4>Content 2 is dimmed</H4>
    </div>

    GROUP 3<BR>
    <input type="radio" id="abc5" name="abc3"  onclick="showabc();"/>
    <label for="abc5"> Yes </label>
    <input type="radio" id="abc6" name="abc3"  onclick="showabc();"/>
    <label for="abc6"> No </label>
    <div id="dpabc9">
    <H4>Content 3 item 1 in its own div</H4>
    </div>
    <div id="dpabc11">
    <H4>Content 3 item2 in its own div</H4>

CURRENT JAVASCRIPT I NEED TO REWRITE WITHOUT A BUNCH OF IF STATEMENTS FOR EACH ELEMENT

function showabc() {    

        if (document.getElementById("abc1").checked == true) {
        document.getElementById("dpabc1").style.opacity = 1.0;
            }

            else {
        document.getElementById("dpabc1").style.opacity = 0.5;  
            }

        if (document.getElementById("abc3").checked == true) {
        document.getElementById("dpabc7").style.opacity = 1.0;
            }

            else {
        document.getElementById("dpabc7").style.opacity = 0.5;  
            }

        if (document.getElementById("abc5").checked == true) {
        document.getElementById("dpabc9").style.opacity = 1.0;
        document.getElementById("dpabc11").style.opacity = 1.0;
            }

            else {
        document.getElementById("dpabc9").style.opacity = 0.5;
        document.getElementById("dpabc11").style.opacity = 0.5; 
            }       
        } 

BEGINNING OF CODE REVISION HERE'S WHERE I'M STUCK. What I'm trying to do is match the variables in "checkMe" with the variables in dimMe. You can see abc1 & 3 need to show the opacity change of one item where abc5 needs to change to opacity to two items (dpabc9 & dpabc11).

function showabc() {
    var checkMe = ["abc1" , "abc3" , "abc5" ];
    var dimMe = ["dpabc1" , "dpabc7" , "dpabc9, dpabc11"];

        for (var i=0, l=checkMe.length; i<l; ++i) {
            document.getElementById(checkMe[i]).style.opacity = 1.0;
            }

            else {

            document.getElementById(checkMe[i]).style.opacity = 0.5;
            }

        }

Answer №1

To optimize the structure of HTML elements by using <fieldset> and assigning values of yes/no, I propose implementing the following JavaScript code:

function toggleOpacity(){
    // 'this' refers to the bound element:
    var divs = this.getElementsByTagName('div'),
        confirmed = this.querySelector('input[type="radio"]:checked');
    
    for (var i = 0, len = divs.length; i < len; i++) {
        divs[i].style.opacity = confirmed.value === 'yes' ? 1 : 0.5;
    }
}

var fieldsets = document.getElementsByTagName('fieldset');

for (var i = 0, len = fieldsets.length; i < len; i++) {
    fieldsets[i].addEventListener('change', toggleOpacity);
}

View JS Fiddle demo here.

This script is designed to work with the following HTML layout:

<fieldset>
    <legend>GROUP 1</legend>
    <input type="radio" id="abc1" name="abc1" value="yes" />
    <label for="abc1">Yes</label>
    <input type="radio" id="abc2" name="abc1" value="no" />
    <label for="abc2">No</label>
    <div id="dpabc1">
       <H4>Content 1 is dimmed</H4>
    </div>
</fieldset>

<fieldset>
    <legend>GROUP 2</legend>
    <input type="radio" id="abc3" name="abc2" value="yes" />
    <label for="abc3"> Yes </label>
    <input type="radio" id="abc4" name="abc2" value="no" />
    <label for="abc4"> No </label>
    <div id="dpabc7">
        <H4>Content 2 is dimmed</H4>
    </div>
</fieldset>

<fieldset>
    <legend>GROUP 3</legend>
    <input type="radio" id="abc5" name="abc3" value="yes" />
    <label for="abc5"> Yes </label>
    <input type="radio" id="abc6" name="abc3" value="no" />
    <label for="abc6"> No </label>
    <div id="dpabc9">
        <H4>Content 3 item 1 in its own div</H4>
    </div>
    <div id="dpabc11">
        <H4>Content 3 item2 in its own div</H4>
    </div>
</fieldset>

Answer №2

UPDATED HTML

UPDATED FIDDLE

GROUP 1<BR>
<input type="radio" id="abc1" name="abc1"  onclick="showabc('content1',1);"/>
<label for="abc1"> Yes </label>

<input type="radio" id="abc2" name="abc1" 
onclick="showabc('content1',0);"/>
<label for="abc2"> No </label>

<div id="dpabc1" class="content1">
<H4>Content 1 is dimmed</H4>
</div>

GROUP 2<BR>
<input type="radio" id="abc3" name="abc2"  onclick="showabc('content2',1);"/>
<label for="abc3"> Yes </label>
<input type="radio" id="abc4" name="abc2"  onclick="showabc('content2',0);"/>
<label for="abc4"> No </label>
<div id="dpabc7" class="content2">
<H4>Content 2 is dimmed</H4>
</div>

GROUP 3<BR>
<input type="radio" id="abc5" name="abc3"  onclick="showabc('content3',1);"/>
<label for="abc5"> Yes </label>
<input type="radio" id="abc6" name="abc3"  onclick="showabc('content3',0);"/>
<label for="abc6"> No </label>
<div id="dpabc9" class="content3">
<H4>Content 3 item 1 in its own div</H4>
</div>
<div id="dpabc11" class="content3">
<H4>Content 3 item2 in its own div</H4>
</div>

UPDATED JAVASCRIPT

function showabc(cssClass,makeBold) {
    var elements = document.getElementsByClassName(cssClass);
    var opacity = 1.0;
    if (makeBold == 0) {
        opacity = 0.5;
    }
    for (var i = 0; i < elements.length; i++) {
        elements[i].style.opacity = opacity;
    }
}

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

Allow images to be uploaded using the browser-policy package in Meteor

Can anyone help me figure out how to use Sir Trevor JS in Meteor for uploading images without encountering this error message? When attempting to load the image 'blob:http%3A//localhost%3A3000/a28ef7dc-ee51-4290-9941-6b8fc317e685', I am receivin ...

Apps created with PhoneGap will maintain the original sizing of web pages and not automatically resize for display on Android devices

After successfully porting my web-based tool to Android using PhoneGap from my Github repository, I encountered an issue with the display on Android devices. The app loads up too big for the screen, forcing me to constantly scroll around to see and access ...

Having trouble displaying a table accurately in React

My goal is to create a table with Material UI in React, similar to the one shown in this image: https://i.stack.imgur.com/QIV8o.png Below is the code I have written so far for this table: return ( <> <div className="main-wrapper& ...

Trigger a popup using the javascript .link() method

I am currently using ag-grid to present JSON data. When the values are located within nested objects, I have to utilize a valueGetter from the grid API to map to the appropriate value. The value getter returns a value for each row and the grid matches it t ...

Using Leaflet to make geojson XMLHttpRequests

Recently, I've been exploring the world of JavaScript and attempting to map around 2,200 data points in Leaflet. Despite following a helpful tutorial on pulling data from a geojson file and displaying it on a map, I can't seem to make it work wit ...

Using AJAX to update content based on selected value in a dropdown menu

My challenge lies in ensuring that a select box retains the selected value from a database entry and triggers an onchange event during form editing or updating. While I have successfully populated the data in the select box based on other selections, I a ...

Click on the image button within an anchor tag using Selenium

Can someone help me figure out how to select an Image Button that looks like the code below using Selenium in C#? I've attempted to find the element using Xpath. <a onclick="resetValues();UploadFile();" href="#"> <img alt="Upload Selected ...

Angular filter that replaces underscores with spaces

Looking for a solution to replace underscores with spaces in a string ...

Creating a list of items using HTML tags should be coded in a way that fits neatly within the main container element

UPDATE: I've come across this code that seems to be functioning somewhat as desired. You can view it live at UPDATE - It's still not aligning properly within the #main div! I've experimented with both 100% and 990px for width in #menu span, ...

Eliminating a line break that appears after incorporating a list into a paragraph

Currently, I am in the process of developing a website where I need to input information. To display this information, I decided to use a list within a paragraph. However, I noticed that after the list name, the text moves to another line which is not wh ...

Display the chosen alternative in a Bootstrap dropdown menu

I am currently facing an issue with the dropdown list in my bootstrap menu. <li class="dropdown"> <a aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="dropdown-toggle" href="#">Chose option<span class="c ...

Ensure that the table is padded while keeping the cells collapsed

I am currently working on creating a table with borders between each row. However, I am facing an issue where the row borders are touching the outer border of the table. Despite my efforts, I have been unable to find a solution to this problem. I feel like ...

Encountering a Runtime Exception while setting up a Client Component in the latest version of Next JS (v13.3

I am facing an issue with a component in my Next JS website. When I attempt to convert it into a Client Component, the page fails to load in the browser and I encounter the following unhandled runtime exception: SyntaxError: "undefined" is not va ...

Identify when a mouse hovers within 10 pixels of a div using jQuery

Is it possible to detect when a user hovers over a specific area within a div using JavaScript or jQuery, without adding any additional tags? -------------------------------- -------------------------------- -------------------------------- -------- ...

Including an anchor element with a specified URL, alongside passing the URL as a property

Having trouble passing a URL to href using a property. I'm attempting to pass the {props.github} value to href, but it's not working as expected. I've set up a property object with a field called github like this: export const projectList ...

The HTML code displays the changes in output after resizing the screen

Currently, I am utilizing canvas(graph) within my Angular JS UI5 application. My main goal is to increase the width of the graph. However, whenever I attempt to adjust the size of the Graph, it remains unchanged. Interestingly, when I shrink the screen, th ...

Validation in AngularJS is limited to only accepting integers with the use of the

Can you help me with validating positive integer numbers using the ng-pattern attribute? Currently, I have this pattern: ^[0-9]{1,7}(\.[0-9]+)?$/, but it also allows decimal values. I want to restrict it to only accept whole numbers. ...

Change the order of the table data elements using the nth-child CSS selector

I need the second td in my table to appear on top of the first one when I resize the screen. @media screen and (min-width: 200px) and (max-width: 872px) { td :nth-child(1) {display:bottom} td :nth-child(2) {display:top} } <table border="0" cell ...

Storing a MySQL query result in a global array in a Node.js environment

Just diving into the world of Node.js and Express, I'm trying to wrap my head around asynchronous functions and global variables. Specifically, I'm working on connecting to a MySQL database, fetching query results, and displaying them on a test.h ...

Looking to remove a specific field from a URL with jQuery

I am trying to extract a specific tag from a string, like in this example: url = 'https://example.com/tag33?tag=17&user=user123'; The goal is to retrieve the value of the tag. If anyone has a solution or suggestion on how to achieve this, ...