Placing a point on a measurement scale according to a changing factor

I am completely new to html, css, and javascript. My goal is to create a color gradient bar and then place a dot on it based on a variable. I tried to implement a solution I found from various sources, but it is not functioning as expected, and I am seeking help to understand the issue.

var A = 38,
  B = 100,
  C = 0,
  D = 300,
  score = 67; // {{crFlag['value']}} will be variable

function init() {
  $('.circle').attr('style', 'left: ' + ((score - A) / (B - A) * (D - C)) + 'px');
};
.container {
  position: relative;
  display: flex;
  width: 300px;
  height: 16px;
  border: 1px solid #7c7676;
  background-image: linear-gradient(to right, #4cd964, #d0ff00, #e0740f, #ff2d55);
}

.circle {
  background: rgba(88, 83, 83);
  width: 10px;
  height: 16px;
  border-radius: 30%;
  position: absolute;
  left: 40px;
}
<div class="container">
  <div class="circle"></div>
</div>

Why is the position of the dot not changing when I update the score variable?

Answer №1

Just a couple of points to consider:

1) If you've been invoking your init function prematurely, it might be because you're calling it before the DOM has finished loading, and therefore before the div with the class "circle" exists. I've included a new script block at the end to ensure it gets called at the right time.

2) It's unclear whether you're utilizing jQuery in your code, but the syntax you're using is jQuery-specific. The snippet provided will function without jQuery, but feel free to uncomment the line I've left commented out if, and only if, you've already loaded jQuery.

<html>
    <head>
        <style>
            .container {
            position: relative;
            display: flex;
            width: 300px;
            height: 16px;
            border: 1px solid #7c7676;
            background-image: linear-gradient(to right, #4cd964, #d0ff00, #e0740f, #ff2d55);
            }

            .circle {
            background: rgba(88, 83, 83);
            width: 10px;
            height: 16px;
            border-radius: 30%;
            position: absolute;
            left: 40px;
            }

        </style>

        <script>
            var A = 38,
            B = 100,
            C = 0, 
            D = 300,
            score = 67; // {{crFlag['value']}} will be variable

            function init(){
                    document.querySelector(".circle").setAttribute("style", 'left: ' + ((score-A)/(B-A)*(D-C)) + 'px' )
                // $('.circle').attr('style', 'left: ' + ((score-A)/(B-A)*(D-C)) + 'px' );
            };
        </script>

    </head>

    <body>
        <div class="container">
            <div class="circle"></div>
        </div>
    </body>
    <script>
    init();
    </script>
</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

Guide on displaying a tooltip for an object in an Angular component using Bootstrap syntax

i have a data object structured like this var obj = {"test price type ty dynamic ": 10, test: 7, pricetype1u: 0, Price type 3: 0, Price type 2: 0} in my Angular component HTML, with Bootstrap styles applied, I've written the following code ...

Instead of stacking neatly, the Bootstrap rows are overlapping each other

I am currently working on a webpage design using bootstrap. The layout consists of different sections, each containing a bootstrap row within a container. However, I encountered an issue where new rows are not appearing below the previous row as expected, ...

Tips for acquiring the newest router in an angular environment

Is there a way to retrieve and store the URL of the latest router that the user has visited in local storage? Any suggestions would be greatly appreciated. Thank you! ...

Update Refresh Token within Interceptor prior to sending request

I'm stuck on this problem and could use some guidance. My goal is to refresh a user's access token when it is close to expiration. The authService.isUserLoggedIn() function returns a promise that checks if the user is logged in. If not, the user ...

How to horizontally center a div between two floated elements

Check out this JSFiddle example. I'm facing a challenge in horizontally centering the div class="filter-group" between two floated buttons within the given example. I've tried various methods but haven't been successful so far. Any assistan ...

Gliding along a div and concealing it out of view, making it seem like it has disappeared

I attempted to slide down the ".preloader" div after a 2-second delay using JQUERY, but I couldn't get it to work as expected. I didn't want to use a toggle button for this effect. I also experimented with creating an animation using @keyframes, ...

Uploading files to a server using Node.js without the need for additional frameworks

I am currently working on a basic file uploading website and I am utilizing the XmlHTTPRequest to handle file uploads. So far, I have dealt with this process only in the context of a server that was already set up for file uploading. Now, however, I need t ...

Changing the arrow in jQuery's slideToggle for different div elements is a breeze

Good day, I'm struggling with getting the arrow switch to work correctly for slideToggle. Even though I have three of them, the arrow changes only for the first one - no matter which div I click on. Any suggestions on what I might be missing? Thank yo ...

Div element to animate and vanish in a flash

I'm attempting to create a smooth slide effect for a div element before it disappears. Below is the code I am currently using: function slideLeft(element) { $("#" + element).animate({ left: "510" }, { duration: 750 }); document.getEle ...

Limiting the number of times a specific character appears using a regular expression

Currently, I am in search of a regular expression that allows me to set a limit on the number of times a special character can appear. For instance, if I want to restrict the occurrence of * to a maximum of 5 times in the entire text, then the output shou ...

What is the best way to transfer variables in my specific scenario?

As I consider the optimal approach for managing my controllers, I find myself faced with a challenge of passing data between them. In my setup, I have multiple controllers that require sharing data throughout. For the first controller: app.controller(&a ...

I am working on a NodeJs code that utilizes (Array)Buffers and native readUInt16BE. However, since I am working within a browser context, I plan to opt for DataView.getUint16 instead

While working on adapting a JPEG parsing function in Node.js for use in a browser environment, I discovered that the original code can be found here. The challenge lies in using Node.js' Buffer class. To make it compatible with a browser environment, ...

Defining the style class for a nested Angular 2 component

Located inside my.component.html <nested-component [class]="nestedClass"></nested-component> Now, when wanting to utilize my component, both style classes need to be specified: <my-component class="my-component-style" nestedClass="nested- ...

The unit tests are not triggering the execution of setTimeout

Currently, I am developing a project in TypeScript and for unit-tests, I am utilizing QUnit and sinonjs. One of the functions within my code dynamically renders UI elements. I need to retrieve the width of these dynamic elements in order to perform additio ...

Please refrain from refreshing the page multiple times in order to receive updated data from the database

Currently, I have created a countdown timer from 00:60 to 00:00. However, once the timer reaches 00:00, I am looking to refresh the page only once in order to retrieve a new value from the database. Does anyone have any suggestions on how to achieve this ...

Understanding the user's preference for text alignment and managing how the text is displayed in a text area (or text field) within a ReactJS application

My latest project is an app that features multiple text areas. Personally, I use the app with two languages - English and another language that is aligned to the right. However, the default setting has the text-areas aligning to the left. To change this ...

Angular encountered an issue with an HTTP POST request, as the 'Access-Control-Allow-Origin' header was not found on the requested resource

I have been attempting to transmit data to a servlet using Angular HTTP POST requests. var httpPostData = function (postparameters, postData){ var headers = { 'Access-Control-Allow-Origin' : '*', &a ...

Using jQuery to retrieve the TD value

I'm attempting to retrieve the TD value using the Value attribute.... Let's say I have the following HTML markup: <td nowrap="nowrap" value="FO2180TL" class="colPadding" id="salesOrderNumber1">bla bla </td> So, I tried this- v ...

Ways to conceal a div using ng-hide

Is there a way to make a div disappear using ng-hide? I have this code and I'm trying to hide the div with id="ApagarNA". The code displays a table with values, but some rows contain N.A in all 4 columns, and I want to hide those specific rows. For e ...

Can a javascript variable be accessed after loading an iframe and returning to the page?

Using a jquery plugin known as colorbox, my colorbox simply opens an iframe on the screen. This detail may not be relevant, as the core issue at hand is that I have 3 variables on my parent window that are retrieved from an AJAX call using jquery: data.re ...