Adjust the increment of the CSS class property

Just a quick query! I'm attempting to adjust the css width property through JavaScript in this manner:

document.getElementById("progressvalue").style.width = "80%";
.progress {
  width: 100%;
  max-width: 500px;
  border: 3px solid black;
  height: 20px;
  padding: 1px;
}

#progressvalue {
  height: 100%;
  width: 0%;
  background-color: #05e35e;
}
<div class="progress"> 
  <div id="progressvalue"></div>
</div>

Rather than setting it to 80% in the JavaScript code, I would like to increase the width by 20%. In other words, (width = width + 20%). I want to apply this adjustment only once (so I can reuse it under different conditions), hence the need for this approach (width = width + 20%)

Answer №1

If you want to retrieve the numerical portion of an element's style.width property, you can extract it and add it to your step value (e.g., 20%).

const step = 5;

const updateProgress = () => {
  const currentWidth = Number(document.getElementById("progressvalue").style.width.replace("%", ""));
  
  if (currentWidth >= 100) {
    return;
  }
  else {
    document.getElementById("progressvalue").style.width = `${currentWidth + step}%`;
  } 
}

You can test this functionality on CodePen.

Answer №2

If you're looking to add some animation effects, using recursion with setTimeout is a great approach:

function animateProgress(value) {
    value += 25;

    document.getElementById("progress").style.width = value + "%";
    if (value < 100) // Stop the animation when progress bar is full
        setTimeout(function () {
            animateProgress(value);
        }, 1500)
}
animateProgress(0); // Initiate the animation

Answer №3

There will be a 20% increase every half second.

let percentage = 0;

setInterval(() => 
{
    if(percentage > 100) {
        clearInterval();
        return;
    }
    document.getElementById("progressbar").style.width = percentage + "%";
    percentage += 20;
}, 500);

Answer №4

Here is a solution for you:

    var progressElement = document.getElementById("progressvalue");

    var elementWidth = progressElement.style.width;

    var newWidth = `${20+parseInt(elementWidth.substring(0, elementWidth.length-1))}%`
    progressElement.style.width=newWidth;

This code assumes that the initial width of the element is set in percentage format.

Answer №5

<button type="button" id="changeButton" onclick="increaseWidth()">Adjust the size</button>

<script>
function increaseWidth() {
  let bar = document.getElementById("progressbar");
  let style = window.getComputedStyle(bar, null).getPropertyValue('width');
  let currentWidth = parseFloat(style);
  bar.style.width = (currentWidth + 15) + '%';
}
</script>

Answer №6

Give it a shot

//clientWidth: retrieves the width of an element's content
var progress_width = document.getElementById("statusbar").clientWidth

document.getElementById("statusbar").style.width = progress_width + (10*progress_width/100) +'px' ;

Answer №7

To achieve the desired outcome, ascertain the present width of the

<div id="progressvalue"></div>
element and store it in a variable. Proceed to augment this value by 20 before assigning the modified result back to the same
<div id="progressvalue"></div>
.

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

Are there any concerns about memory leaks when using recursive JavaScript Objects?

Our model entities are passed through the API in JSON format, allowing us to inflate them client-side for use on both the server and client sides. These entities have standard Hibernate bi-directional relationships. As you navigate through an object in the ...

Divide the strings within an array

When working with nodejs, I utilize walksync to obtain an array as shown below: var paths = ['Essential Classes.jade' , 'introduction.jade'] These are the filenames contained within a folder. The objective is to extract only the filen ...

The value of an object is replaced when a general method is called for the second time

I seem to be missing a fundamental concept in programming as I am encountering an unusual issue that I have never faced before. Let me illustrate my problem through this code snippet: var result = {abc: 10, cde: 20, efg: 30}; var final_result = {}; var c ...

Ajax requests across different domains are unsuccessful, even when attempting to access a file on

I have a local html file that contains an ajax function attempting to retrieve xml content from x.com. When I run the file, it only works in Internet Explorer and fails in Firefox and Safari browsers. This issue is likely due to the Same Origin Policy. H ...

Can a secondary non-static, privileged function be implemented in a jQuery Plugin?

Most of the jQuery tutorials I've encountered tend to focus on using a single main public function for their selection plugins. By 'selection' plugin, I am referring to one that is more complex than just a static function added to jQuery. F ...

Ajax is coming back with a value that is not defined

Currently, I am working on a search function that is responsible for searching a name from the database. When the user clicks "add", the selected item should appear below the search field so that it can be saved in the database. However, I am encountering ...

Discovered an issue with Sentry debugging where a lengthy string is being returned as undefined

We are currently in the process of developing an Angular 1.x application that utilizes Bootstrap components. Recently, we integrated Sentry debugging into our site and encountered the following error: 'PAPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDIN ...

Input the selected checkbox options into the designated text field

My form consists of 3 arrays of checkboxes - hummus[], mayo[], jam[]. Currently, the jQuery functions disable the remaining checkboxes once the required number is checked. Query: I am attempting to transfer the values of the checked checkboxes into text f ...

How can I avoid using the appendTo method in jQuery?

There seems to be an issue in my HTML code, could you please take a look at the code snippet below: HTML: <div class="agent_select_wrap"> <select name="menu-114" class="wpcf7-form-control wpcf7-select" aria-invalid="false"> <op ...

The alignment of the label on the Watu Quiz does not match with the Radio Button

I've encountered an issue with a Watu quiz I created where the labels are not aligning with the radio buttons. Any suggestions on how to style this and fix the alignment? You can view the page here. Here is a screenshot for reference: https://i.sst ...

You are unable to assign mutations in Vuex

Dealing with a peculiar problem where "val" and "ok" can be used within "console.log()", but for some reason, state.user cannot be assigned any value. However, state.user does display 'ok' on the website. export const state = () => ({ user: ...

Challenges Arising from CGI Scripts

One requirement for the user is to input text into a designated text field within a form element in my HTML. Following this, a CGI script processes the user's input and JavaScript code is responsible for displaying the processed information. JavaScri ...

Elevate the element from the choice API to the organization API using this.$parent

I recently developed a Vue 3 component called "Tab" using the option API. Here is the code: export default { name: "Tab", props: { name: {required: true}, iconClass: {required: true}, selected: {default: false} }, da ...

Ways to hide notifications by setting a timer while keeping the delete option visible

Presently, this is the code I am working with using Javascript and Vue.js. I have an array called Messages.length that contains messages. When the x button is clicked, it triggers the "clearMessages(item)" function on the server side. However, I also aim ...

Incorporating rounded corners to an embedded YouTube video

Check out this JSFiddle link. The border-radius property appears to be working correctly at first, but then the rounded corners suddenly disappear shortly after loading. Is there a way to apply rounded corners to YouTube videos that are embedded on a webp ...

Is it a bad idea to incorporate JavaScript functions into AngularJS directives?

I came across this snippet of code while working with ng-repeat: <div ng-show="parameter == 'MyTESTtext'">{{parameter}}</div> Here, parameter represents a string variable in the $scope... I started exploring if it was possible to c ...

Google Chrome - flexbox - container element

Please check out this code snippet in Chrome: codepen example html: <div class='flexbox'> <div class='static'>ddd </div> <div class='flex'> <div class='flex-child'> < ...

Guide to creating varying component sizes using ReactJS and Styled Components

Is it possible to add variation to my button based on the prop 'size' being set to either 'small' or 'medium'? interface Props { size?: 'medium' | 'small'; } How can I adjust the size of the component us ...

Combining Files with Gulp.js and Handling File Names

I need a solution that will add the file name as a comment to each file in the stream. This means creating a comment line with the file path in the final destination file. The current functionality is as follows: pseudocode: concat(file1, file2) # outpu ...

Is there a way for me to identify the vertical gaps in my code using JavaScript?

Within this specific HTML document, there are multiple div elements that have an absolute positioning applied to them I am looking to develop a JavaScript code that can determine the row of each individual div. I define a row as any space on the vertical ...