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

When I try to call jQuery's getScript function, the callback does not execute as expected within

When I invoke the script in a function at runtime function CheckOutMyFace() { $.getScript("/scripts/jtimers.js", function (data) { }); }; I notice in Firebug that the script is being called every time the function is invoked, but for some reason the ...

Angular Recursive Bootstrap Breadcrumb Guide

I am looking to implement the bootstrap breadcrumb component (https://getbootstrap.com/docs/4.0/components/breadcrumb/) in my project. My goal is to use the breadcrumb to show the entire path to the current directory within a component that resembles a di ...

In my app.post request in node.js and express, the body object is nowhere to be found

Having an issue with node.js and express, trying to fetch data from a post request originating from an HTML file. However, when I log the request, the req.body object appears empty. I've added a console.log(req.body) at the beginning of my app.post(" ...

Unable to require less after installing it using npm in a Node.js environment

Running on mac os x version 10.10.5 Checking my node and npm versions. node -v v4.2.1 npm -v 2.14.7 Following the instructions on the official less website, I installed less globally. sudo npm install -g less sudo npm install -g less-plugin-clean-css ...

Are you searching for a stylish tabbed navigation menu design?

I am searching for a tabbed navigation menu specifically designed to showcase images as the tab items. Here is an example of what I have in mind: <div class="menu"> <a href="#"> <img src="images/Chrysanth ...

What is the best way to use a button to hide specific divs upon clicking?

Is there a way to use a button onclick event to hide specific divs within a parent div? I've tried using .toggleClass('.AddCSSClassHere') but I'm not sure how to apply it to multiple divs. The jQuery snippet provided only allows me to h ...

Creating unit tests for linked functions in Node.js using Jest

Hey there! I'm looking to test a function using Jest that involves token verification and requires 3 parameters. Here's the code for the function: const verifyToken = (req, res, next) => { // Checking for token in header or URL parameter ...

The output when evaluating the xpath query "html/body/div/text()[1]" shows as [object Text], indicating there may be an issue with accessing the element's text using Selenium

My goal is to retrieve the value "479" from the given HTML snippet: <div data-testid="testid"> "479" " Miles Away" </div> In my Python Selenium script, the code I am using looks like this: xpath = 'html/b ...

Anchor positioning within Firefox Mobile (for Android)

I created a homepage with multiple sections, each linked to from the main menu: <body> <header> <!-- nav used on all pages --> <a href="#nav" class="toggle-nav"> menu <i class="fa fa-bars">< ...

Using an HTML element to pass a variable into a replace function

I am looking to highlight a 'SearchString' by replacing it with <span style="background-color: yellow">SearchString</span> within a targetString. The SearchString varies, so I am wondering how I can make this happen. This is what I ...

Having trouble generating an HTML table from JSON data using JavaScript

My attempt to generate a table with data from an external .JSON file using JavaScript is not working as expected. Everything worked fine when the data was hardcoded into the .JS file, but once I tried to fetch it externally using "fetch", the details do no ...

Vertical text frozen at the top of a table

My goal is to design a table with frozen threads and vertically oriented labels in the header. I have made an attempt at implementing this below, but as a newcomer to CSS, I am facing several challenges. One issue I've encountered with my solution ...

Execute functions during jquery's .animate() operation

This is a snippet of code I use to smoothly scroll the browser back to the top: $('html, body').animate({scrollTop: 0}, 500, "easeOutQuart"); Now, I am looking for a way to prevent the user from scrolling while this animation is running. Once t ...

The request to remove the product from the server at URL http://localhost:8000/product/[object%20Object] encountered an internal server

I'm having trouble setting up the AJAX delete method. I keep getting a 500 internal server error and despite following tutorials, I remain frustrated. Can someone please help me correct my code? This is using Laravel 5.8 and jQuery 3.3. <section ...

firefox compatibility issues with jquery ajax

Trying to establish a connection with a URL and expecting a large object in response has proven to be challenging. The process appears to function smoothly until an error occurs during the return reply, triggering the .ajax.error() function. Unfortunately, ...

Tips for swapping out a div tag with another div tag in the same spot without needing to redirect to a different page by utilizing bootstrap

Currently, I am developing a JSP project that utilizes Bootstrap for the frontend. I have come across a question regarding HTML design. Is there a way to replace one div tag with another div on the same page without navigating to a new URL using Bootstrap ...

Issues with playing Html 5 video arise when making an ajax call

My goal is to implement an AJAX call followed by displaying an HTML5 video. The provided code snippet seems to be ineffective. $.ajax({ type: "POST", url: "Videos.aspx/GetBlocs", contentType: "application/json; charse ...

Comparison between Static HTML controls and Razor HTML helpers.Static HTML controls are

Just starting to learn ASP.NET MVC and I've noticed that it generates controls like @Html.TextBoxFor(x => x.Name) which resemble server-side controls in web forms. Since browsers only understand HTML, these controls need to be converted to HTML bef ...

Is it possible to transfer an image from the client to the NodeJS server and store it locally within the server itself?

Is there a way for me to upload an image from the client side, send it via an HTTP request (POST) to the server (NodeJS), and save it internally on the server? Whether using Jquery, XMLHttpRequest, or a form, I continue to face the same issue where I can& ...

Create a div element containing a captivating background image that automatically scales to fit any browser window

Currently, I am facing a challenge with scaling background images within a shared div (framework) so that they can resize along with the browser. I have searched for solutions involving Javascript, but none seem to address my specific case. Any assistance ...