Ensuring that objects remain fixed in place regardless of window resizing is a common task in web development, often achieved through a

I've been attempting to create range sliders with boxes that display the slider's current value, but I'm having trouble getting them positioned correctly when the window size changes. Despite trying various solutions found online, I resorted to manually moving a box alongside the slider thumb. However, as my window shrinks or expands, the boxes don't stay in place. Does anyone have any suggestions on how I can keep them positioned correctly, regardless of the window size?

Below is the code I'm working with (Note: this is just for testing purposes and not a finalized version):

<html>

<head>
    <title>Home</title>

    <!-- CSS -->
    <link rel="stylesheet" href="stylesheet.css">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

    <!-- JQuery -->
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>

<body>

    <div id="login-box">
        <div id="logo"><img border="0" src="logo.png"></div>
        <div id="text_boost">Boost your account now!</div>

        <div id="slider1"><input id="range1" type="range" min="10" max="100" value="0" step="1" onchange="change(1)"></div>
        <div id="slider2"><input id="range2" type="range" min="0.5" max="4" value="0" step="0.5" onchange="change(2)"/></div>
    </div>


    <div id="sliderInfo1" class= "ui-widget-content" style="background-color: #d9d9d9; border-radius:10px; width: 59px;
                                                          height: 22px; text-align:center; display: table">
        <span style="line-height: 22px"></span>
        <div style="display: table-cell; vertical-align: middle; text-align: center; font-size:12px;"><span id="slider_1">10.000</span></div>
    </div>

    <div id="sliderInfo2" class= "ui-widget-content" style="background-color: #d9d9d9; border-radius:10px; width: 59px;
                                                          height: 22px; text-align:center; display: table">
        <span style="line-height: 22px"></span>
        <div style="display: table-cell; vertical-align: middle; text-align: center; font-size:12px;"><span id="slider_2">500</span></div>
    </div>

<script type="text/javascript">
    var newPoint, newPlace, offset;

    var savedOffset_1 = document.getElementById("sliderInfo1").getBoundingClientRect().top - 
                    document.getElementById("range1").getBoundingClientRect().top;
    change(1);

    var savedOffset_2 = document.getElementById("sliderInfo2").getBoundingClientRect().top - 
                    document.getElementById("range2").getBoundingClientRect().top;
    change(2);

    function change (id) { 
        var el = $("#range" + id);
        var top = el.position().top;
        var left = el.position().left;

        var bodyRect = document.getElementById("range" + id).getBoundingClientRect(),
            elemRect = document.getElementById("sliderInfo" + id).getBoundingClientRect(),
            offset_2   = elemRect.left - bodyRect.left;

        if(id == 1) {
            offset_1 = savedOffset_1;
        } else if(id == 2) {
            offset_1 = savedOffset_2;
        }

        // Measure width of range input
        var width = 430;

        // Determine placement percentage between left and right of input
        newPoint = (el.val() - el.attr("min")) / (el.attr("max") - el.attr("min"));

        offset = -1;

        // Calculate new box position
        if (newPoint < 0) { 
            newPlace = 0;
        } else if (newPoint > 1) { 
            newPlace = (bodyRect.left - width); 
        } else { 
            newPlace = width * newPoint + left + width + (59 / 2); 
            offset -= newPoint; 
        }

        // Move box
        $("#sliderInfo" + id).css({ position: "fixed", left: newPlace, marginLeft: offset + "%", top: top - offset_1 - 5 + "px",
                                width: 59 + "px", height: 22 + "px", display: "table", fontSize: 12 + "px", 
                                backgroundColor: "#d9d9d9", borderRadius: 10 + "px", verticalAlign: "middle", textAlign: "center",
                                lineHeight: 22 + "px"})
                         .text(numberWithCommas(el.val() * 1000));

    }

    function numberWithCommas(x) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    }

    </script>
</body>

My CSS: http://pastebin.com/rASpFWjN

https://i.sstatic.net/0v1JB.png

https://i.sstatic.net/lqTlY.png

Answer №1

When you set elements to have a fixed position, you'll need to handle the window.onresize and window.onscroll events in order to correctly position your labels. This is because elements with position: fixed are always relative to the viewport of the browser. So, an element with

position: fixed; top: 100px; left: 100px
will always remain 100px from the top left corner of the window, regardless of window size or scrolling.

However, using position: fixed in your situation may unnecessarily complicate the code. You can simply position the labels inside the slider divs so that they remain relative to the sliders.

<div id="slider1">
  <div id="sliderInfo1" class="sliderInfo">
    <span id="slider_1">10.000</span>
  </div>

  <input id="range1" type="range" min="10" max="100" value="0" step="1" />
</div>

<div id="slider2">
  <div id="sliderInfo2" class="sliderInfo">
    <span id="slider_2">500</span>
  </div>

  <input id="range2" type="range" min="0.5" max="4" value="0" step="0.5" />
</div>

This approach also reduces the need for extensive position calculations in JavaScript.

function change(id) {
  var thumbWidth = 28;
  var el = $("#range" + id);
  var inputWidth = el.width() - thumbWidth;
  var newPoint = (el.val() - el.attr("min")) / (el.attr("max") - el.attr("min"));
  var newPlace = inputWidth * newPoint;

  // Adjust the new left position by adding half of the thumb width to it.
  newPlace += (thumbWidth / 2);    

  $("#sliderInfo" + id).css({
    left: newPlace,
  }).text(numberWithCommas(el.val() * 1000));
}

You can see a full example of this on https://jsfiddle.net/dnm7qr6j/

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

Applying class to target specific screen size in Bootstrap

I've been utilizing bootstrap for my project. My objective is to assign multiple classes based on screen size, such as sm-col and xs.col. For example, let's say I have a text id <div id="text" class="xs-format lg-format ..."></div> ...

Unable to alter the default error message within the jquery-validation plugin

I recently came across a post discussing how to change default error messages in jQuery validation. You can check it out here. After reading the post, I decided to modify my js code by adding the following lines to jquer.validate.min.js: jQuery.extend(jQ ...

Troubleshooting Issue with Nested ng-include in AngularJS: Difficulty arises when the parent element with the ng-include attribute is dynamically added using the ng-

Click here to see a demo plunker that will help you understand my issue. On my main page, I have a table. Each table row is followed by a hidden empty row. When the first row is clicked, I use a directive to inject HTML into the empty row below it. Main ...

Having trouble showing the text on the screen, but after checking my console, I notice empty divs with p tags. Surprisingly, the app is still functioning properly without any

Currently, I am developing a joke app entirely on my own without any tutorials. One of the components in the app is SportsJokesApi, which retrieves data from a local json folder (SportsJokesData) that I have created. Here is how it is structured: const Sp ...

Creating dynamic HTML elements for each section using JavaScript

Is there a way to dynamically add a task (input + label) for each specific section/div when entering the name and pressing the "Add" button? I attempted to create an event for each button to add a task for the corresponding div of that particular section, ...

Using a jQuery if statement to target a particular div and apply custom CSS styling

I have encountered a unique challenge that I am struggling to solve. Imagine I have a 3x3 table created using div elements, and one of the cells has a background color of #999. My goal is to use jQuery to check if a specific cell has this background color, ...

What is the significance of the "@" in JXON conversion in JavaScript?

Looking at an XML structure like the one below: <calendar> <month year="2013" num="5"> <day num="1"> </month> </calendar> I decided to convert it to JSON using MDN's JXON Snippet 3. https://developer.moz ...

Using Pug/Jade, be sure to call a function during each loop iteration

I'm attempting to develop a basic app, similar to a TO-DO LIST. I want to generate divs dynamically (with incremental ids) when a Button is clicked and then enter some text into an HTML input field. For example: <div id="item1"> <div id="ite ...

Which is quicker when utilizing jQuery selectors: selecting by .classname or div.classname?

Which is quicker: using $(".classname"). or adding the tag to search for as well? $("div.classname") In my opinion, using just the classname would be faster because jQuery can simply loop through all classnames directly, whereas in the second example i ...

The element referenced by `$(this)` in jQuery seems to be

I have multiple forms on a single page that are very similar in structure. Some of the forms contain elements with a css class that triggers an onchange event handler. This is in an ASP.NET MVC environment. $('.check-changes').on('change&apo ...

Angular4 allows for the creation of a div that can horizontally scroll

Below is the HTML code I am working with: <div class="card-deck" fxLayout.xs="row" style="overflow: scroll; height:100%"> <md-card style="width:10rem" *ngFor="let make of filteredMakes" (click)="goToModels(make.niceName)" class=" ...

Applying box shadow to input group addon in Bootstrap 3 using CSS

What I am trying to achieve is that when I click on the inputbox or selectbox, the box shadow defined in my CSS should also cover the input-group-add-on feature in Bootstrap 3. The issue I'm facing is that the input-group-add-on does not display the ...

Error: The value provided is not compatible with the HTMLInputElement interface

I am currently attempting to submit a form using jQuery-ajax, but I keep encountering the following error when trying to submit the form on click: TypeError: Value does not implement interface HTMLInputElement Here is the JavaScript code I am using: ...

"Exploring the Interaction Between Solr, Tomcat, and CORS

Currently, I have Solr 4.3 running on Apache Tomcat 9 as a webapp for a CRM product to provide indexes. To perform a search on the indexes, I am querying Solr using the following URL: http://localhost:8888/solr-intranet-int/intranet_users/suggest?q=(surn ...

Tips for preserving data while attempting to access the schema

Attempting to store data from a book that includes author and genre information, referenced in separate files. The issue arises when making the reference in the main schema. Although the book carries details of the book itself, it fails to establish refer ...

Plugin for controlling volume with a reverse slider functionality

I have been customizing the range slider plugin found at to work vertically instead of horizontally for a volume control. I have successfully arranged it to position the fill and handle in the correct reverse order. For instance, if the value is set to 7 ...

Tips for arranging Radio buttons in multiple columns within the same Radio group in Material UI

As a newcomer in the world of React.js, I am feeling a bit anxious about posting my question on Stack Overflow. I hope everyone can overlook my lack of experience and forgive me for any mistakes. I have been struggling to find the right solution to my prob ...

Tips for successfully incorporating a jQuery plugin into your React project

I'm attempting to incorporate the Air Datepicker library by t1m0n into my React application, but I'm encountering difficulties. import React from 'react'; import AirDatepicker from 'air-datepicker'; class Datepicker extend ...

I am curious about when the CSS of my website will start impacting its search engine ranking

Initially, my perception of CSS was that it was only used for styling the appearance of a document when viewed in a browser. However, I soon came to realize that search engines also utilize CSS for indexing web pages. It is said that search engines do not ...

ES6 Set enables the storage of multiple occurrences of arrays and objects within

Review the script below. I'm currently testing it on Chrome. /*create a new set*/ var items = new Set() /*add an array by declaring its type as an array*/ var arr = [1,2,3,4]; items.add(arr); /*display items*/ console.log(items); // Set {[1, 2, 3, ...