Tips for modifying the "width" of a style within an HTML template implemented in a NodeJs express application

Currently, I am facing a challenge in dynamically adjusting the width value for a <div> element serving as a coloured bar within an HTML template used for PDF generation. While I can successfully set other values using something like {{my_value}}, applying a similar approach to style attributes does not yield the desired outcome.

My attempts have included using width: {{my_value}}% and assigning a class to the div with a specified width i.e.

.divClass { "width": {{my_value}} }

The HTML template snippet is shown below:

<!-- Dynamically update width based on {{my_value}} -->
<div style="width: 45% !important;">
<!-- Dynamic percentage displayed inside and beside -->
<div style="padding-left:8px;">{{my_value}}%</div>
</div>

Within the JavaScript file, we have the following code segment:

// Retrieve the value from POST request
var val1 = req.body.val1;

//substitute the value in the template
templateHtml = templateHtml.replace('{{my_value}}', val1);

In essence, if the POST val1 = 20%, my goal is to ensure that the coloured bar <div> reflects only 20% of its total width while also displaying the corresponding percentage. However, at present, although I can display the percentage on the bar, it ends up filling the entire width with color instead.

Answer №1

If the server response includes a percentage value, let's say percentage, you can adjust the size using JavaScript like this:

To change the size of a <div> element in a JS file, use:

document.getElementById("myDiv").style.width = '50px';

Here is a simple example:

document.getElementById("updateLoadBar").onclick = function() {
    updateLoadingBar()
};

function updateLoadingBar() {
    // Get input value
    // Assuming you retrieve the value from your template as follows:
    // width = {{ percentage }};
    var width = document.getElementById("input-number").value;
    // Set darkBlue width
    document.getElementById("myBar").style.width = width + '%';

    // Preventing text overlap
    if (width >= 5) {
        // set text
        document.getElementById("text").textContent = width + "%";
    }
}
.myButton {
  border-radius: 5px;
}

#myProgress {
  width: 100%;
  height: 40px;
  margin-top: 10px;
  background-color: lightblue;
}

#myBar {
  width: 1%;
  height: 100%;
  background-color: darkblue;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
Select a number between 0 and 100:
<input id="input-number" type="number">
<input id="updateLoadBar" type="button" value="Update load bar" class="myButton">


<div id="myProgress">
  <div id="myBar">
    <div id="text">
    </div>
  </div>
</div>

You can explore ready-to-use examples on pure JS or bootstrap documentation if you are utilizing bootstrap in your project. Hopefully, this information is beneficial.

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

CSS3 variables causing issues

I want to streamline my CSS file by setting up generic variables that can be used throughout to ensure consistency and organization. For example: @shadow: 6px 6px 10px rgba(0,0,0,0.2); .shadow { box-shadow: @shadow inset; } However, when I try to a ...

How come my directive is being updated when there are changes in a different instance of the same directive?

For the purpose of enabling Angular binding to work, I developed a straightforward directive wrapper around the HTML file input. Below is the code for my directive: angular.module('myApp').directive('inputFile', InputFileDirective); f ...

What is the best way to assign attributes to multiple HTML elements using an array?

Seeking assistance to hide various sections in my HTML file upon button click, with the exception of one specific section. Encountered an error message: Uncaught TypeError: arr[i].setAttribute is not a function Here's a snippet of my code: const hide ...

The unzipper will disregard any empty directories within the file

I am a Japanese Web Developer. Unfortunately, I struggle with English. https://www.npmjs.com/package/unzipper This library is currently in use by me. Below you will find my code snippet: // unzip module import fs from 'fs-extra' import unzip ...

The issue with Internet Explorer failing to adhere to the restrictions set on maximum width and

I'm attempting to scale my images precisely using CSS: HTML: <div id="thumbnail-container"> <img src="sample-pic.jpg"/> </div> CSS: #thumbnail-container img { max-height: 230px; max-width: 200px; } In this scenario, ...

Every time I attempt to utilize React BrowserRouter, I inevitably run into an error

Every time I set up a new React application and incorporate react-router-dom, I often run into the following error message in the console. Despite attempting various fixes Warning: Invalid hook call. Hooks can only be called inside of the body of a functio ...

How can I toggle the visibility of a div based on whether a variable is defined or not?

How can I display a specific div on my webpage only when certain variables in PHP pull out a specific result from a database? I attempted to use the code snippet below, but it's not working as expected. Can someone provide guidance on how to achieve ...

What is the process for retrieving User Information using AngularJS following NodeJS authentication?

While I've come across similar questions on this topic, my lack of experience with Angular and Node is making it difficult for me to find a suitable solution. I had previously written this code that successfully handled the login process and allowed ...

Box Pattern with Pop-Up Modal

Check out the grid of squares I've coded below: <div class='square-container'> <div class='square'></div> <div class='square'></div> <div class='square'></div& ...

Extracting values from an *ngFor loop in Angular 8 - Here's how to do

Currently, I am utilizing *ngFor to display some data. I have a requirement to extract a specific value from *ngFor and display it in, for instance, my heading. However, when I attempted to use {{ project }}, it consistently returned undefined. Despite hav ...

Access not granted while utilizing Yeoman for scaffolding an application

Having some trouble setting up a new project with Yeoman and Angular. I've tried running "yo angular" and "yo app", but keep encountering the same error message. Unfortunately, I'm not very familiar with Terminal. Error: EACCES, permission denie ...

Hide object scroll percentage with CSS styling

Is there a way to dynamically hide an element based on the user's scrolling behavior? I have incorporated floating social buttons into my website, and I am looking for a solution that will hide them when the user reaches the bottom of the page (foote ...

Incorporate CSS and JavaScript files into every page of NetSuite

Is there a way to globally apply a CSS file or JavaScript code to all NetSuite pages in order to change the page direction to RTL? I attempted adding it through: SuiteScript >> Client >> Deployment : All Records, While I was able to successfully add them ...

swap out a method within a publicly available npm module

Currently, I am using an API wrapper package that utilizes the request module for making API requests. While this setup works well in most cases, I am facing a situation where I need to use this package in a node-webkit environment and replace the request ...

I'm experiencing an issue with my Next.js Airbnb-inspired platform where I am unable to save a listing to my favorites

While working on my Next.js Airbnb clone project, I encountered an issue with adding a Listing to favorites. The heart button component's color does not change when clicked, despite receiving a success response. Moreover, the addition to favorites is ...

What causes RangeError: Maximum call stack size exceeded when Element UI event handlers are triggered?

I'm currently working on setting up a form and validating it with Element UI. Despite closely following the documentation, I am encountering an issue where clicking or typing into the input boxes triggers a RangeError: Maximum call stack size exceeded ...

Every time I click once, two unnecessary AJAX calls are triggered, and the DOM remains outdated until I manually refresh the page

Whenever I click on a span, it sends an ajax request to delete the clicked todo from the database. However, in the DOM, the item is not removed until I refresh the page. Here is my index.html file: <ul class="list"> </ul> I noticed ...

Ensuring that environment variables are properly set is essential for effective error handling

I am currently integrating my NodeJS and Typescript App to create new config files that utilize .env variables. If a specific variable is not set, I want to trigger an error. After setting up my config file, I encountered some errors; however, I am unsure ...

The rollup-plugin-typescript is unable to identify the 'lib' option within the 'compilerOptions'

Currently, I'm following a tutorial on how to create an npm package. The tutorial can be found here. Here is the content of my tsconfig.json file: { "compilerOptions": { "target": "es5", "module": "es2015", "sourceMap": tr ...

Node application on OpenShift encountering an error: Unable to locate version `ZLIB_1.2.9' of /lib64/libz.so.1

Greetings to all in the Stackoverflow community, I'm a newcomer here! Recently, I encountered an error while deploying my personal NodeJS app on OpenShift Online (free starter account) that requires the NPM package sharp (https://www.npmjs.com/packag ...