Is there a way to incorporate a JavaScript variable as the value for CSS width?

I created a scholarship donation progress bar that dynamically adjusts its width based on the amount donated. While I used CSS to handle the basic functionality, I am now trying to implement JavaScript for more advanced features. My goal is to calculate an integer value based on different ranges of donation amounts, which will then be used in an equation to determine the pixel width of the progress bar. Here is my current code snippet where I have attempted to achieve this, but it only displays the last calculated number. Any help with refining the logic would be greatly appreciated. Thank you!

<script>
{
    var amount = 1163; //example amount
    var x = 0;

    if (0 < amount < 500) {
        x = 0;
    } if (500 < amount < 1000) {
        x = 1;
    } if (1000 < amount < 1500) {
        x = 2;
    } if (1500 < amount < 2000) {
        x = 3;
    } if (2000 < amount < 2500) {
        x = 4;
    } if (2500 < amount < 3000) {
        x = 5;
    }
        document.write(x)
}
</script>

Answer №1

In the realm of javascript, comparisons don't function in that manner. It is imperative to explicitly define each logical comparison using ANDs and/or ORS.

if (0 < amount && amount < 500) { ... } // or x < 500 whichever logical course

Following operator precedence, this translates to (0 < 1163 < 500)

Subsequently, this simplifies to (true < 500) Given that 1 == true, all of these evaluations result in true, hence x will consistently be 5.

Answer №2

To achieve the desired outcome, it is recommended to steer clear of logical tests and focus on optimizing your code. Consider the following approach:
x=Math.round(amount/500+.5)-1;
http://jsfiddle.net/scraaappy/erL37s8k/

Answer №3

Take a look at this amazing code snippet: http://jsfiddle.net/wdth4eme/3/

{
var amount = 1163; //example amount
var x = 0;

if (0 < amount && amount < 500) {
    x = 0;
} if (500 < amount && amount < 1000) {
    x = 1;
} if (1000 < amount && amount < 1500) {
    x = 2;
} if (1500 < amount && amount < 2000) {
    x = 3;
} if (2000 < amount && amount < 2500) {
    x = 4;
} if (2500 < amount && amount < 3000) {
    x = 5;
}
   document.querySelector(".inner").style.width=Math.floor(100/x)+"px";
}

Answer №4

If you want to adjust the size of an element without touching the CSS, you have the option to alter it through JavaScript.

let newWidth = 300;
document.getElementById("bar").style.width = newWidth + "px";

(assuming the id of the target element is called "bar" and the desired width in pixels is stored in the variable newWidth).

Answer №5

Only proceed when you are within the specified range. If it is below a certain number, it cannot exceed that limit.

function determineValue(val) {
if(val < 500) return 0;
if(val < 1000) return 1;
if(val < 1500) return 2;
...
...
}

var result = getValue(1235)

//output: 2

Answer №6

To start, it is essential to use logical operators for matching purposes, such as x>0 && x<=50

For example, in HTML:

<div id="foo">....</div>

In CSS:

#foo { width: 100px; }

You can modify it using JavaScript by:

document.getElementById('foo').style.width = "500px";

or

document.getElementById('foo').style.width = x + "px";

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

Dynamic container elements (already arranged)

After creating a marksheet generator, I noticed that the divs positioned over an image on the resulting page are not responsive when trying to print. The print preview ends up looking strange and distorted. How can I make these already positioned divs resp ...

Can you provide some examples of CSS code snippets?

Can someone share some CSS codes similar to :hover that can be used in the : part for different effects? I tried looking it up but couldn't find much, so any help would be greatly appreciated. ...

What is the reason for DialogContent displaying a scroll bar instead of expanding further when nested Grids with spacing are included?

My current project involves working on a form displayed in a dialog window. To adjust the layout of the form's fields, I utilize multiple Grid elements nested within another Grid. However, I've encountered an issue where adding any spacing to the ...

Save user information to initialize rootScope upon refreshing the page

I'm looking for a way to retain a User Json Object in such a manner that I can use it to initialize my $rootScope.user Json Object with the saved information even after refreshing the page. The storage should persist as long as the browser window rem ...

Bringing in an SVG file as a React component

When importing an SVG into React as a Component, I am facing an issue where the CSS classes are wrapped in style tags, causing an error upon import. Removing the CSS from the style tags allows the SVG to load, but it loses its additional styling. I want t ...

Troubles with DropDownList onChange event when selectedIndex is at 0

Hey there, I have a question that's been puzzling me. I have three security question dropdown menus on my ASPX page with JavaScript that removes and repopulates questions based on user selection. Everything works great when editing an existing profile ...

Is Kendo Telerik grid capable of applying conditional formatting while filtering?

Is it feasible to modify the background color of rows in a Kendo Telerik grid when a filter is implemented within an ASP.NET MVC application? ...

Is it preferable to include in the global scope or the local scope?

When it comes to requiring a node module, what is the best approach? Should one declare the module in the global scope for accuracy and clarity, or does declaring it in the local scope make more sense? Consider the following examples: Global: let dns = r ...

Implement a background image in the navigation bar links using CSS

Strange as it may seem, the image refuses to show up in the navbar. Adding borders or other styling makes it visible, but not the image itself. If I manually include the image using the <img/> tag in the HTML, it appears, but then the hover effect do ...

Retrieving results from PostgreSQL database using pagination technique

When I'm pagination querying my data from a PostgreSQL database, each request involves fetching the data in this manner: let lastNArticles: Article[] = await Article.findAll({ limit: +req.body.count * +req.body.page, or ...

JavaScript API for Outlook appointment object

Is there a way to change the appointment busy status "show as" to out of office using JavaScript in an Outlook web add-in? Also, how can I alter the value of all day event to true (tick it) using JavaScript in an Outlook web add-in? Any insights would be ...

Troubleshooting the problem with JavaScript's week start date

I am encountering an issue with JavaScript when trying to obtain the first day of the week. It seems to be functioning correctly for most cases, but there is a discrepancy when it comes to the first day of the month. Could there be something that I am ove ...

"Discover the process of transforming HTML, CSS, and script files into a cohesive JavaScript format

I have developed a unique web chat widget from scratch using HTML, CSS, JavaScript, and AJAX calls. Now, my goal is to convert it into a script that can be easily embedded in any other websites or webpages. Similar to how third-party widgets work, users sh ...

Is there a way to include an image in a serialized file?

What is the method to include image_form into form in Django? form - form.serialize() image_form - image $('#id_submit').click(function(e) { e.preventDefault(); var form = $('form').serialize(); image_form = $("#id_image")[0].f ...

Alert displayed on console during transition from MaterialUI lab

Whenever I try to run my MUI application, an error pops up in the console It seems you may have forgotten to include the ref parameter in your forwardRef render function. import { LoadingButton } from "@mui/lab"; const LoadData = ({loading,sig ...

Implementing two background images and dynamically adjusting their transparency

With the challenge of loading two fixed body background-images, both set to cover, I encountered a dilemma. The text on the page was extending below and scrolling, along with top and bottom navigation icons. As expected, the second background covered the f ...

Extracting the value of an attribute from an XML element and converting it into an HTML unordered list with

Here is an example of an xml file structure: <root> <child_1 entity_id = "1" value="Game" parent_id="0"> <child_2 entity_id="2" value="Activities" parent_id="1"> <child_3 entity_id="3" value="Physical1" parent_id="2"> ...

Save a collection of controller instances within a separate controller in AngularJS

I am in need of an angular example where one controller wraps another. For instance, I am looking to divide some logic between EndpointListController and EndpointController. EndpointListController will handle retrieving data from storage, along with funct ...

Implementing hashing with resumable.js

Looking for a way to include hashing in resumable.JS by utilizing the "fileAdded" event hook. Any suggestions on how to add hash to each chunk? ...

Creating a custom toJSON function for a property declared using Object.defineProperty

Let's consider a scenario where we have an object with a specific property that is meant to reference another object, as shown below: Object.defineProperty(parent, 'child', { enumerable: true, get: function() { return this._actualCh ...