Want to know how to center the value of a slider range input in your React project using NextJS and Tailwind

Can someone help me with the issue I'm having with the offset? Is there a way to link a value to the thumb?

I've tried two methods, but one gives a significant offset and the other gives less. However, it seems more like a workaround than a solution. Any suggestions?

I require precise center positioning.

First method trick: https://i.sstatic.net/N8A1g.png

Second method trick: https://i.sstatic.net/dqcnp.png

import { useEffect, useState } from "react";

function Slider() {
  const [value, setValue] = useState(50);

  useEffect(() => {
    const tooltip = document.getElementById("tooltip");
    const maxValue = document.getElementById("slider").getAttribute("max");
    const val = document.getElementById("slider").getAttribute(value);
    const center = (value / maxValue) * 100 + "%";

    if (tooltip) {
      tooltip.style.left = center;
    }
  });
  
  // Code for handling bubble range removed for demonstration purposes

  return (
    <>
      <div className="range-wrap relative flex h-[24px] w-full items-center">
        <input
          className="range relative flex w-full"
          aria-valuemin={0}
          type="range"
          min="0"
          max="100"
          value={value}
          id="slider"
          onChange={({ target: { value: radius } }) => {
            setValue(radius);
          }}
        />
        <div id="progress"></div>
        <div
          id="tooltip"
          className="bubble absolute top-[-40px] left-1/2 flex h-[38px] w-[32px] -translate-x-1/2 items-center justify-center rounded-full bg-purple-400 align-middle text-body-medium text-white"
        >
          {value}
        </div>
      </div>
    </>
  );
}

export { Slider };

Answer №1

Give this code a shot.
substitute useEffect with the following:

  useEffect(() => {
    const range = document.querySelector("input[type=range]");
    const tooltip = document.getElementById("tooltip");

    let thumbSize = 8;
    const ratio = (range.value - range.min) / (range.max - range.min)
    let amountToMove = ratio * ((range.offsetWidth - thumbSize) - thumbSize) + thumbSize
    tooltip.style.left = amountToMove+"px"
  }, [value]);

Then, in return(), insert this block of JSX

      <div className="range-wrap relative flex h-[24px] w-full items-center">
        <input
          className="range relative flex w-full"
          aria-valuemin={0}
          type="range"
          min="0"
          max="100"
          value={value}
          id="slider"
          onChange={({ target: { value: radius } }) => {
            setValue(radius);
          }}
        />
        <div id="progress"></div>
        <div
          id="tooltip"
          className={`bubble absolute top-[-40px] flex h-[38px] w-[32px] -translate-x-1/2 items-center justify-center rounded-full bg-purple-400 align-middle text-body-medium text-white`}
        >
          {value}
        </div>
      </div>

This should operate as anticipated. 👻

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

Answer №2

I also adopt a similar approach where I pay close attention to the top and left values (-right-[1.1rem] for instance). It may not be the optimal solution, but it serves its purpose well for me.

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

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

My goal is to develop a custom forEach function that retrieves a substring from each element in an array

I have a file containing image names like: sciFi.png, posed.png, birdA.png, dolphin.png, horse.png, shake.png, loft.png, basement.png, avenger.png, friend.png In my JavaScript document, I am trying to read this file and convert it into an array. Then, I w ...

The import Alias was not recognized by the React Jest test

I'm struggling with a React Jest test for a Button component where an import is not recognized. Can anyone suggest why the test is failing to recognize this import? Component: import ... import ... from 'styled-components'; import ... from ...

creating a function that sends two separate fetch requests with a pause in between each request

Currently, I am working with 2 endpoints. The first one requires a "post" request, and upon receiving the response, it should provide me with an ID that is used in the URL of the second endpoint. To ensure that I can obtain this ID before proceeding with ...

Creating a Self Closing Alert Message in AngularJS: A Step-by-Step Guide

Just getting started with AngularJS and looking to create a self-closing message. How can this be accomplished? I'm aiming for similar results as the question found here: How to Automatically Close Alerts using Twitter Bootstrap However, I want to ...

What causes the useEffect hook to render twice in a Next.js application?

Within my Next.js application, I am seeking a way to verify whether a user has permission to access a particular page. While using a context, I encountered an issue where my useEffect hook was returning both the updated and default values. How can I ensure ...

Filter a div based on multiple conditions using JavaScript/jQuery

In my filtering system, I have two sections: place and attraction. When I select a place, the corresponding div is displayed according to the selected place. Similarly, when I select an attraction, only the attractions are filtered accordingly. <ul clas ...

Basics of CSS border-image explained

Although it seems simple, I'm struggling to figure out what the issue might be. I am attempting to create a div with a specific border on an ASP.Net webpage. CSS: .ResourcesDiv { border-image:url(http://blogrope.com/wp-content/uploads/2013/06/003-w ...

Tips for concealing the final click (add) tab after it has been clicked and revealing the hidden (add) button when the user clicks on the remove button

I have created a form where users can add tests. Everything is working smoothly but I want the previous "Add Another Test" field to be removed when the user clicks on it and a new field to be shown. Everything is running well, but the issue is that when t ...

The 'onChange' event in React is being triggered only once

Currently utilizing material-ui Library Below is my React component: import Checkbox from '@material-ui/core/Checkbox'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import React from "react"; import { withStyles ...

Writing the success function for a jQuery ajax call involves defining the actions to be taken once

Embarking on my journey to learn jQuery and web development, I am faced with the task of sending user input (username and password through a submit button) to a PHP page using .ajax and success function. Below is the HTML form code: <form id="form1"&g ...

Unlocking the Sound: Using a Custom Button to Activate Audio on HTML Video in React

While working on a project, I encountered a small issue: I have a video tag in my code: <video muted autoPlay loop src={video}> I simply want to add a single custom button/control to toggle between muting and unmuting the video. I'm thinking of ...

What methods can I use to generate unique paths within a URL for a website, and how can I assign a distinct status to each path?

I have developed a JavaScript program that allows you to draw using canvas. I have now set up a web server with Node.js in order to enable drawing on the website. Each specific drawing will be saved as a unique URL path so that you can resume where you lef ...

Using Vanilla JavaScript to Disable a Specific Key Combination on a Web Page

On a completely random English-Wikipedia editing page, there exists a way to add content (for example, "test") and save it using the existing key combination of Alt+Shift+S. My goal is to specifically prevent this action without removing the save button b ...

Struggling with integrating Bootstrap 4 Modals in Angular 2 environment

I attempted to incorporate a modal from into my navbar, but nothing happens when I click on it. <div class="pos-f-t fixed-top header"> <nav class="navbar navbar-inverse bg-inverse navbar-toggleable-md"> <button class="navbar- ...

Assigning a unique identifier to a button that will vary depending on the selected radio input

UPDATED HTML: The circumstances have changed because I am no longer in my office, but the concept remains unchanged. The situation is that on a certain part of a website, users have the option to choose from multiple saved addresses. Each address has a un ...

Struggling to align text to the far left within a text area using Bootstrap

When I accidentally place my cursor earlier in the text area, it starts writing from that point, leaving some unwanted spaces at the beginning. I prefer it to start from the extreme left, similar to how it behaves in input boxes. Below is the code snippet ...

Error: The 'length' property cannot be searched for using the 'in' operator

Hmm, I keep getting an error that says "Uncaught TypeError: Cannot use 'in' operator to search for 'length' in" Every time I attempt a $.each on this JSON object: {"type":"Anuncio","textos":["Probando ...

What is causing the #wrapper element to not fully contain all of its content within?

I am struggling to figure out why the wrapper on this page is not properly wrapping the content. It's only 332px tall for some reason when it should be the height of the content, which is causing the footer to pull up to the top of the page. Could I b ...

Display HTML content repeatedly depending on the number selected in a dropdown menu using AngularJS

I need your assistance with a dropdown selection feature on my website. The idea is that based on the number chosen from the dropdown, I want to dynamically repeat sections in HTML. For example, if I select 3 from the dropdown menu, the page should display ...

Keep the active button state when it is clicked in React JS within a functional component

When I click on a button, I want to remain in the section while also having the button stay in the background with a color that indicates my selection. This could be for breakfast, lunch, dinner, or any other section. const Categories = ({ categories, fi ...