Transform percentage into pixels

I'm currently utilizing this specific JavaScript range slider and my goal is to define a minimum and maximum value in pixels, rather than the default percentage range from 0 to 100.

I have successfully implemented the min and max settings, now my next challenge is converting all the percentage values to pixel amounts. I managed to achieve this for the drag function, but I'm facing difficulties applying it to the value.

For example, when I set the value to 50, instead of reaching 50px, it defaults to 50%. How can I convert all the percentages to pixels?

If there is a more efficient method to achieve this, please share your insights.

I believe the key code that needs adjustment is in the final function named initDragger:

cachePosition = ((config.value / 100) * range[!isVertical ? 'offsetWidth' : 'offsetHeight']);
dragger.style[!isVertical ? 'left' : 'top'] = (cachePosition - (woh / 2)) + 'px';

JSFiddle

function rangeSlider(elem, config) {

  // JavaScript range slider code here

}

var slide = document.getElementById('range-slider');
var resultP = document.getElementById('results');
var button = document.getElementById('button');

rangeSlider(slide, {
  value: 50,
  drag: function(v) {
    document.getElementById('results').innerHTML = "Your Current Value is: " + v;
  },
  max: 60
});
.range-slider-track {
  height: 20px;
}
.range-slider-track:before {
  content: "";
  display: block;
  width: 100%;
  height: 2px;
  background-color: black;
}
.range-slider-track .dragger {
  display: block;
  width: 10px;
  height: inherit;
  position: relative;
  background-color: red;
}
<div id="range-slider"></div>
<p id="results"></p>

Answer №1

It has become a bit of a tradition for me now, so here is my answer.

document.getElementById('clickme').onclick = function() {
  document.getElementById('slider').value = 37;
};
<input type="range" min="2" max="40" value="23" id="slider" />
<button id="clickme">Set "pixel" to 37</button>

Often, the simplest solution is the best one.

Answer №2

https://github.com/tovic/simple-custom-range-slider - make sure to scroll all the way down on this page for the solution:

let minValue = 5, maxValue = 50;

function convertPixelToPercent(pixelValue) {
    return ((pixelValue - minValue) / (maxValue - minValue)) * 100;
}

function convertPercentToPixel(percentValue) {
    return ((percentValue / 100) * (maxValue - minValue)) + minValue;
}

rangeSlider(document.getElementById('range-slider-1'), {
    value: convertPixelToPercent(15),
    drag: function(newValue) {
        document.getElementById('result-area').innerHTML = Math.round(convertPercentToPixel(newValue));
    }
});

Answer №3

It seems a bit clunky and is slightly off by 5px, starting at 21px, so it requires some fine-tuning. The function tickDragDist() is based on this code. This function calculates the distance between the elements .dragger and .tick within the .range-slider (with .tick serving as the reference point).

Check out the working example at this link.

You can also view the illustration here: https://i.sstatic.net/NKImi.png

        function rangeSlider(elem, config) {
    
          var html = document.documentElement,
            range = document.createElement('div'),
            dragger = document.createElement('span'),
    tick = document.querySelector('.tick'),
            down = false,
            rangeWidth, rangeOffset, draggerWidth, cachePosition;
    
          var defaults = {
            min: 20,
            max: 150,
            value: 0, // set default value on initiation from `0` to `100` (percentage based)
            vertical: false, // vertical or horizontal?
            rangeClass: "", // add extra custom class for the range slider track
            draggerClass: "", // add extra custom class for the range slider dragger
            drag: function(v) { /* console.log(v); */ } // function to return the range slider value into something
          };
    
          for (var i in defaults) {
            if (typeof config[i] == "undefined") config[i] = defaults[i];
          }
    
          function addEventTo(el, ev, fn) {
            if (el.addEventListener) {
              el.addEventListener(ev, fn, false);
            } else if (el.attachEvent) {
              el.attachEvent('on' + ev, fn);
            } else {
              el['on' + ev] = fn;
            }
          }
    
          var isVertical = config.vertical;
    
          elem.className = (elem.className + ' range-slider ' + (isVertical ? 'range-slider-vertical' : 'range-slider-horizontal')).replace(/^ +/, "");
          range.className = ('range-slider-track ' + config.rangeClass).replace(/ +$/, "");
          dragger.className = ('dragger ' + config.draggerClass).replace(/ +$/, "");
    
            // Event listeners for mouse interactions
            ...
    
          function updateDragger(e) {
            // Function to update the dragger position based on user input
            ...
          }
          
          function initDragger() {
            // Function to initialize the dragger and set its position based on initial value
            ...
          }
    
            // Additional code for the range slider setup
            ...
    
          range.appendChild(dragger);
          elem.appendChild(range);
    
          initDragger();
    
        }
    
        // Initialize the range slider
        ...
    
        // Calculate the distance between .tick and .dragger elements
        function tickDragDist() {
            ...
            return dist;
        }
    .range-slider-track { height: 20px; }
    
    .range-slider-track:before { content: ""; display: block; width: 100%; height: 2px; background-color: black; }
    
    .range-slider-track .dragger { display: block; width: 10px; height: inherit; position: relative; background-color: red; }
    
    .range-slider-track .tick { height: 5px; width: 0; position: absolute; left: 0; top: calc(50% - 2.5px); display: inline-block; }
<div id="range-slider">
  <label for="range-slider" class="tick">0</label>
</div>
<label for="results">Lengths:
  <output id="results"></output>
px</label>

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

Improving the efficiency of JSON data retrieval in JavaScript

I possess a hefty 10MB JSON file with a structured layout comprising 10k entries: { entry_1: { description: "...", offset: "...", value: "...", fields: { field_1: { offset: "...", description: "...", ...

What is the reason behind Istanbul's code coverage reporting a switch statement as uncovered even though all conditional paths are covered?

Within my node.js application, there is a class that includes a getter method with a significant switch statement. Rather than the simple example provided below, this switch statement contains numerous unreleased product-specific values replacing 'a&a ...

Leveraging Material-UI: Utilize props in useStyles method while employing Array.map()

After delving into the world of passing props to makeStyles in Material-UI, I stumbled upon this insightful answer. The solution presented involves passing props as a variable, which is quite useful. However, my aspiration is to extend this functionality t ...

Vue.js is having trouble locating images

I am currently using Vue-CLI with the latest version of Vue (3.9.3), but I am facing an issue where Vue cannot locate my images. Below are some screenshots for reference. Why are the images not showing up? First image (Structure) Second image (template) ...

What is the best way to position an image beside a jquery dialog box?

Apologies for not finding a suitable topic to discuss. Is it possible to place an image next to a jQuery dialog, similar to the following example? If so, how can this be achieved? ...

Deploying a pair of GitHub repositories to a unified Azure web application

Although this isn't exactly a technical question, I couldn't find a more appropriate stackexchange site for it. Recently, I made the move to Azure for deploying my backend web applications and APIs. I discovered that it's possible to deploy ...

Handling Exceptions in Node.js and Express

Having recently delved into the world of javascript and node, I've been working on creating an application using node.js and express. While I've implemented appropriate error callbacks in my code, there are instances where the node.js server abr ...

Passing arguments to an external function in jQuery from a dynamically loaded Ajax page

Despite its confusing title, the issue at hand is actually quite simple. My homepage contains a script that loads an external PHP file for a specific section of my website. Within this PHP file, I need to call a function from the main JavaScript file (th ...

Encountering the error "ReferenceError: __extends is not defined" is a common issue when modifying the rollup.config.js commonjs function in projects that use the ReactJS library

Currently, I am involved in a project and there is also a library project containing all the common components used throughout. Within this library, I had to integrate a component that relies on materialUI. However, upon trying to export this component, I ...

Avoid an excessive number of XHR/AJAX requests when using the Facebook embedded iframe

I am facing an issue with a Bootstrap Carousel that contains multiple social embeds from Facebook, all of which have videos. The problem is evident on this simple jsfiddle due to the Facebook embed. If you visit this page: https://jsfiddle.net/1L95vqn4/, ...

JavaScript class syntax allows for the definition of inherited instance fields

In the code snippet below, I have implemented a way to define a prototype with a simple property that can be inherited by objects using the prototype: const SCXMLState = Object.setPrototypeOf( Object.defineProperties({ addChild() { } isStat ...

What is the process for defining the host in a websocket connection?

When working on my page, I establish a websocket connection to the server using ws://127.0.0.1:5000/ws in development and ws://www.mymachine.com/ws when deployed to production. Is there a more efficient way to handle this so that I don't have to manua ...

Is there a way to apply an event function after adding elements through append?

When I click the button, a div is appended inside the body. However, I am trying to make it so that when I click on this newly appended div, an alert message pops up. I have tried implementing this with a highlighted area, but have been unsuccessful. How c ...

Nuxt project encountering issues with loading JS files

I've been integrating a bootstrap template into my Nuxt project but seem to be facing some challenges with loading the necessary scripts. I've attempted to import the scripts into my nuxt.config.js file in a couple of ways: 1.) Initially, I tri ...

Can anyone identify the result produced by this line of code? Utilizing the $.get method to access "http://192.168.4.1:80/" with the parameter {pin:p}

Can anyone explain the output of this line of code? $.get("http://192.168.4.1:80/", {pin:p}); I understand that it is an Ajax code that sends data through a GET request, but I am trying to manually send the same data like this ".../pin:13" or "", however ...

Is it possible to import files in Vue JavaScript?

I want to incorporate mathematical symbols from strings extracted from a JSON file. While it seems to work perfectly on this example, unfortunately, I encountered an issue when trying it on my own machine. The error message 'Uncaught (in promise) Refe ...

Order of AngularJS Scope.on and Scope.emit Invocation in a Filter

One of the challenges I am facing involves watching a value in one controller that is changed in another controller within my filters. The goal is to determine whether an emit should be triggered based on the updated value. Here's the current situatio ...

An effective method for appending data to a multidimensional array in Google script

Is there a way to expand a multidimensional array of unknown size without relying on a Google Sheets spreadsheet to manage the data? I've searched everywhere but can't find an example for a 3-dimensional array. Here's the challenge I'm ...

Is there a way to stop my <pre> code from being displayed on the page?

Currently, I am utilizing the google code prettifier found at http://code.google.com/p/google-code-prettify/ This tool functions similarly to stack overflow by enhancing and highlighting syntax when a block of code is input. However, I have encountered a ...

The function cannot be called because the type does not have the appropriate signature for invoking. The specific type lacks compatible call signatures, as indicated

Encountering an issue while attempting to utilize a getter and setter in my service, resulting in the following error message: Cannot invoke an expression whose type lacks a call signature. Type 'Boolean' has no compatible call signatures 2349 t ...