Can JavaScript values be passed into CSS styles?

I am currently working on dynamically updating the width of a CSS line based on a JavaScript value (a percentage). The line is currently set at 30%, but I would like to replace that hard-coded value with my JavaScript variable (c2_percent) to make it more dynamic. If anyone has any suggestions or solutions, I would greatly appreciate it. Thank you!


        <div class="bar-graph bar-graph-horizontal bar-graph-one">
            <div class="bar-one">
                <span class="rating-a1">A1</span>
                <div class="bar" id="rating-a1" data-percentage=""></div>
            </div>
            <div class="bar-two">
                <span class="rating-a2">A2</span>
                <div class="bar" data-percentage="11%"></div>
            </div>
            <div class="bar-three">
                <span class="rating-a3">A3</span>
                <div class="bar" data-percentage="7%"></div>
            </div>
            <div class="bar-four">
                <span class="rating-b1">B1</span>
                <div class="bar" data-percentage="10%"></div>
            </div>
            <div class="bar-five">
                <span class="rating-b2">B2</span>
                <div class="bar" data-percentage="20%"></div>
            </div>
            <div class="bar-six">
                <span class="rating-b3">B3</span>
                <div class="bar" data-percentage="5%"></div>
            </div>
            <div class="bar-seven">
                <span class="rating-c1">C1</span>
                <div class="bar" data-percentage="9%"></div>
            </div>
            <div class="bar-eight">
                <span class="rating-c2">C2</span>
                <div class="bar" id="c2-rating" data-percentage=""></div>
            </div>
            <div class="bar-nine">
                <span class="rating-c3">C3</span>
                <div class="bar" data-percentage="5%"></div>
            </div>
            <div class="bar-ten">
                <span class="rating-d1">D1</span>
                <div class="bar" data-percentage="5%"></div>
            </div>
        </div>

    @-webkit-keyframes show-bar-eight {
        0% {
            width: 0;
        }
        100% {
            width: 30%;
        }
    }

    <script>
        for (let i = 0; i < 1; i++) {
            const c2_security_values = Array.from(document.querySelectorAll('.security-value-c2'));
            const c2_security_values_inner = c2_security_values.map((element) => element.innerText);
            const c2_summed_values = c2_security_values_inner.reduce((accumulator, currentValue) => parseInt(accumulator) + parseInt(currentValue));

            const total_security_values = Array.from(document.querySelectorAll('.individual-market-value'));
            const total_security_values_inner = total_security_values.map((element) => element.innerText);
            const total_summed_values = total_security_values_inner.reduce((accumulator, currentValue) => parseInt(accumulator) + parseInt(currentValue));

            const c2_percent = c2_summed_values / total_summed_values;
        }
    </script>

Answer №1

Thinking off the top of my head, I propose adding the following line of code after computing the c2_percent variable in the script (ensure that c2_percent is defined outside the loop and set as a variable, not a constant).

    document.getElementById('c2-rating').setAttribute("data-percentage", c2_percent * 100 + '%');

Without additional information about the page elements, styles, etc., it's uncertain if this code will function properly.

Are you looking to adjust the width of the c2-rating element?

This code only updates the data-percentage attribute value.

If you want to alter the CSS width attribute, you can attempt the following:

    document.getElementById('c2-rating').setAttribute("style","width:" + (c2_percent * 100) + '%');

I've created a snippet to demonstrate that this implementation could work, yet its success depends on the context of your project's webpage.

<html>

<head>
    <style>
        .bar-graph {
            font-family: Arial, Helvetica, sans-serif;
        }

        .bar-graph div {
            padding: 5px 0px;
        }

        .bar-graph div span {
            display: inline-block;
            font-weight: 600;
            margin: 5px 5px;
            float: left;
        }

        .bar-graph .bar {
            border: 1px solid #ccc;
            background-color: #eee;
            height: 30px;
        }

        @-webkit-keyframes show-bar-eight {
            0% {
                width: 0;
            }

            100% {
                width: 30%;
            }
        }

    </style>
</head>

<body>
    <div class="bar-graph bar-graph-horizontal bar-graph-one">
        <div class="bar-one">
            <span class="rating-a1">A1</span>
            <div class="bar" id="rating-a1" data-percentage=""></div>
        </div>
        <div class="bar-two">
            <span class="rating-a2">A2</span>
            <div class="bar" data-percentage="11%"></div>
        </div>
        <div class="bar-three">
            <span class="rating-a3">A3</span>
            <div class="bar" data-percentage="7%"></div>
        </div>
        <div class="bar-four">
            <span class="rating-b1">B1</span>
            <div class="bar" data-percentage="10%"></div>
        </div>
        <div class="bar-five">
            <span class="rating-b2">B2</span>
            <div class="bar" data-percentage="20%"></div>
        </div>
        <div class="bar-six">
            <span class="rating-b3">B3</span>
            <div class="bar" data-percentage="5%"></div>
        </div>
        <div class="bar-seven">
            <span class="rating-c1">C1</span>
            <div class="bar" data-percentage="9%"></div>
        </div>
        <div class="bar-eight">
            <span class="rating-c2">C2</span>
            <div class="bar" id="c2-rating" data-percentage=""></div>
        </div>
        <div class="bar-nine">
            <span class="rating-c3">C3</span>
            <div class="bar" data-percentage="5%"></div>
        </div>
        <div class="bar-ten">
            <span class="rating-d1">D1</span>
            <div class="bar" data-percentage="5%"></div>
        </div>
    </div>

    <input type="range" min="0" max="100" value="0" class="slider" id="c2RatingSlider" value="43" onchange="updateC2()">

    <script>
        updateC2();

        function updateC2() {
            var c2_percent = document.getElementById("c2RatingSlider").value / 100;
            document.getElementById('c2-rating').setAttribute("data-percentage", c2_percent * 100 + '%');

            document.querySelectorAll('.bar').forEach((bar) => {
                const percentage = bar.getAttribute('data-percentage');
                bar.setAttribute("style", "width:" + percentage);
            });
        }
    </script>
</body>

</html>

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

Incorporate my personalized CSS file into the Bootstrap 4 development tools

Is it possible to customize Bootstrap 4 variables with build tools as outlined in this guide? I am wondering how I can create a separate CSS file named MyCustomStyles.css at the end of the build process by running npm build dist. I have created a _MyCusto ...

Using CSS to set the display property to table-cell and converting it to a

I needed a SideMenu that would match the length of the content, but for some reason, using display:table-cell caused it to display:block in both Firefox and Chrome. What could be the reason behind this inconsistency? .back-branded { background: #900; ...

Arranging an array of integers followed by sorting by the decimal part of each value in a particular sequence using JavaScript

Below is an example of sorting an array: let arr = ['100.12', '100.8', '100.11', '100.9']; When sorted traditionally, the output is: '100.11', '100.12', '100.8', '100.9' Ho ...

Delivery person receiving biscuit but my internet browser doesn't seem to be getting it when I attempt to retrieve it

Currently, I am in the process of creating a website using Flask and React. The user is required to input an email and password on a form, which is then sent via axios.post to the backend. The backend checks if the email and password match with the databas ...

Accessing the data from an HTML5 slider using JQuery

Having some difficulty fetching a value from an HTML5 slider using JQuery. Here is my code snippet: JQuery Code: // Getting the value from slider one $("#submit").on("click", function(evt) { var sliderValue = $('#slider01').attr('value ...

Instead of using a hardcoded value, opt for event.target.name when updating the state in a nested array

When working with a dynamically added nested array in my state, I encounter the challenge of not knowing the key/name of the array. This lack of knowledge makes it difficult to add, update, iterate, or remove items within the array. The problem lies in fun ...

Failure to trigger Summernote's OnImageUpload function

After transitioning to the latest version of Summernote, which is Version 7, I encountered a problem with the image upload functionality. Despite specifying the line onImageUpload: function(files) {sendFile(files[0]);}, it seems that this code is not being ...

Placing information within a nested array with multiple levels of nesting

I'll try to keep this concise, Here is the structure of the schema... import mongoose from 'mongoose' const QuestionSchema = mongoose.Schema({ questionTitle: { type: String, required: " title"}, questionBody: { type: Stri ...

Issue with Left Alignment of Tabs in Material-UI

As of now, material-ui's latest version does not provide support for aligning tabs to the left in the component. However, I came across a workaround on this GitHub page I have implemented the same workaround, and you can view it here: Unfortunately, ...

Optimizing normals for unindexed BufferGeometry in Three.js

Currently, I am attempting to refine the normals of a mesh starting from an non indexed BufferGeometry. A similar query has been addressed in the past, however, the Three.js API has undergone significant changes since then and I am unable to make it work o ...

Combine the remaining bars by stacking the highest one on top in Highchart

Making use of stacking to display the highest value as the longest column/bar, with smaller values being merged within the highest one, can create a more visually appealing stack chart. For example, when looking at Arsenal with values of 14 and 3, ideally ...

What is the best method to pass a JavaScript file array to a Node.js server?

Is it possible to transfer data from a Javascript file linked to an HTML page to a Node.js file on a post route without displaying it on the HTML page? If so, what is the best way to accomplish this? ...

Encountering an error when trying to use this.setState

I'm currently working on developing a simple react application that consists of a component. In this component, I am attempting to adjust the state when a link is clicked. However, I'm encountering an issue where the setState function is not bein ...

``Troubleshooting Problem with Tailwind's Flex Box Responsive Grid and Card Elements

Starting point: Preview https://i.sstatic.net/zfzBU.jpg Code : <div class="container my-12 mx-auto"> <div className="flex flex-wrap "> {error ? <p>{error.message}</p> : null} {!isLoading ...

Show specific modal or image depending on various criteria

Seeking guidance on how to achieve the following tasks in a simple manner as my understanding of HTML, Bootstrap, and CSS is basic: 'When radio button #1, radio button #4, and button #2 are clicked, upon submission display modal 1 with an image at a ...

Ways to align Material-UI component side by side

My MenuList and Grid components are currently stacked vertically, but I need them to be aligned horizontally. I'm wondering why the Grid is nested within a div in the rendered HTML code. How can I make these components behave more like floating HTML e ...

Use ajax calls instead of using the bind() function in Drupal for better performance

Currently, I have an AJAX call that is bound to the window popstate event. While it works fine, the issue arises when parsing arguments from the querystring. The problem lies in the fact that the ajax call gets bound to the window on page load, causing the ...

The NVD3 chart embedded in a React application generates HTML elements that persist on the page indefinitely without fading away

In my React application, I integrated an NVD3 scatter chart. However, I have encountered an issue with the tooltip not disappearing when hovering over the chart: https://i.stack.imgur.com/6lLok.png After moving the cursor away from the chart, the tooltip ...

Navigate to a particular date with react-big-calendar

I know this might sound like a silly question, but I am new to working with React. Currently, the React-big-calendar allows users to navigate to specific dates when selected from the Month view. What I want is for the same functionality to apply when a use ...

What is preventing me from binding the array index to a model in AngularJS with two-way binding?

I'm currently facing a challenge with a seemingly simple task: I have an array of string values that I want to link to a select element's options, and then connect the index of the chosen value to a variable. However, I have found that neither us ...