Tips for applying a CSS class to a range slider interval using JavaScript

Is it possible to dynamically assign a CSS class to an element when the value of a range slider is changed? For example, consider the following slider:

<input id="slider" type="range" min="10" max="50">

I have a JavaScript function that retrieves the slider value, divides it by 10, and rounds it up:

let sliderValue = Number(slider.value);
sliderValue = Math.ceil(sliderValue / 10);

//output:
3
2
1
2
3
4
5 etc. as the slider moves.

I am aiming to add a class named active to an element on the page in order to fade it in whenever the slider value changes. Given that this process occurs 10 times per interval, is there a way for JavaScript to detect when the slider value changes and then apply the designated class?


The current application of the "active" class results in stuttering due to it being assigned 10 times per interval. To visualize the issue, here is a link to a CodePen: CodePen

Answer №1

Here are the adjustments I made to enhance the performance:

function customizeColors() {
    const colors = {
        colorOne: {
            name: "Color 1",
            value: 1
        },
        colorTwo: {
            name: "Color 2",
            value: 2
        },
        colorThree: {
            name: "Color 3",
            value: 3
        },
        colorFour: {
            name: "Color 4",
            value: 3
        },
        colorFive: {
            name: "Color 5",
            value: 4
        },
        colorSix: {
            name: "Color 6",
            value: 5
        },
        colorSeven: {
            name: "Color 7",
            value: 2
        }
    };

    const slider = document.querySelector("#slider");

    const updateUI = (dataSet) => {
        let output = document.querySelector("#results");
        output.innerHTML = "";
        dataSet.forEach((d) => {
            output.innerHTML += `<div class="result">
      <h3>${d.name}</h3>
      <p>Color Value Number: ${d.value}</p>
      </div>`;
        });

        function showResults() {
            let results = document.querySelectorAll(".result");
            results.forEach((result) => {
                result.classList.add("active");
            });
        }
        window.setTimeout(showResults, 0);
    };

    const applyFilter = () => {
        let data = Object.values(colors);
        let sliderValue = Number(slider.value);
        sliderValue = Math.ceil(sliderValue / 10);
        let filteredData = data.filter((d) => d.value === sliderValue);

        updateUI(filteredData);
    };

    slider.addEventListener("input", applyFilter);
}

customizeColors();
body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 50vw;
    margin: 5rem auto;
    background: #444;
    color: #f5f5f5;
}

.result {
    margin-top: 4rem;
    background: #c4c4c4;
    padding: 1rem;
    display: block;
    color: #444;
    border-radius: 10px;
    overflow: hidden;
}

.active {
    opacity: 1 !important;
    height: auto !important;
}
<p>Objective: Enhance slider smoothness.</p>
<input id="slider" type="range" min="10" max="50" />
<label for="slider">Slide me</label>
<section id="results"></section>

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

The data retrieved from localStorage following a redirection using $router.push is empty

When I log in using my Login component, a request is made to retrieve a JWT token which is then saved into localStorage before navigating to the Home page. const response = await axios.post('/auth/login', { login: this.login, password: th ...

Adjust the scroll position when the window is resized

Currently, I am using a combination of smooth scroll and IDs/anchor tags to navigate through the content on my website. The code snippet below is designed to fetch the ID of the next 'section' in the DOM and assign it as the href for the 'vi ...

Is there a way to choose all elements in the Bootstrap pagination code using JavaScript?

Recently, I've been working on a website with Bootstrap, and I encountered an issue with the overflow scroll bar that I had to hide using CSS. To navigate the pagination with the mouse wheel, I've been experimenting with JavaScript. I found that ...

Routine specified in AJAX is not getting executed

Is it possible to utilize AJAX to run code on a separate HTML page? In the calling page, the following code is present: $.ajax({ url: 'ajaxcalled2.html', //This is the current doc type: "POST", async: 'false', data ...

Is it more advisable to implement an async iterator through an async generator function, or would it be more efficient to utilize Symbol.asyncIterator?

The following code operates as intended: function pause(time) { return new Promise(resolve => setTimeout(resolve, time)); } async function fetchAsyncData() { await pause(1000); // simulating database/network delay... return [1, 2, 3, 4, 5] ...

Guide to integrating the office-ui-fabric-react library into your current MVC project

Our team has embarked on developing an application and we've decided to integrate it with office-ui-fabric-react. While I am familiar with installing packages using npm, I am unsure about where to install both NodeJs & gulp. I have a repository na ...

Parsing JSON data repeatedly using JavaScript within an HTML environment

The following code I found on a popular web development website works perfectly: <!DOCTYPE html> <html> <body> <h1>Customers</h1> <div id="id01"></div> <script> var xmlhttp = new XMLHttpRequest(); var url ...

Exploring Complex Parent-Child Connections with FeathersJS

Is there an optimal method for managing deep nested parent-child relationships in Feathers using the recommended Association Method? Let's say our data entries look like this: [ {"name": "Grandpa", "id": 1, "parent": null}, {"name": "Mom", " ...

Stop Scrolling in VueJS

I am currently facing a challenge in preventing scrolling only when the lightbox component is open. I prefer not to rely on any external libraries or plugins for this task. Within my App.vue file, I have included the "LightBox" component. Therefore, it se ...

Give a radio button some class

<input id="radio1" type="radio" name="rgroup" value="1" > <label for="radio1"><span><span></span></span>1</label> <input id="radio2" type="radio" name="rgroup" value="2" > <label for="radio2"><span ...

The conflict between Material UI's CSSBaseline and react-mentions is causing issues

Wondering why the CSSBaseline of Material UI is causing issues with the background color alignment of React-mentions and seeking a solution (https://www.npmjs.com/package/react-mentions) Check out this setup: https://codesandbox.io/s/frosty-wildflower-21w ...

Fetching dynamic information via AJAX for a jQuery tooltip

I have successfully loaded content via AJAX, including a UL element with li items that each have tooltips. Now I want to load tooltip content via AJAX for each individual li item. How can I achieve this? Currently, I am making an AJAX call to load the li ...

Angular is unable to successfully send a post request to Node

Whenever I click on the submit button on the frontend, it triggers the upload() function. This is how it is implemented in my app.html: <div class="row" style="padding:10px;"> <button type="submit" class="btn btn-primary" style="margin ...

Having difficulty with building a basic module in Node JS, it's just not cooperating

As a newcomer to Node JS, this platform, and the English language, I apologize in advance for any linguistic errors. I seem to be encountering a "return" error within my code. Specifically, when I include the hi.myFunc(); function, I receive the ...

Modify the appearance of the submit button when the input field is focused

Is there a way to change the button color when an input field is in focus? I'm open to using either JavaScript or CSS for this. Thanks in advance for any assistance. .redbutton { background-color:red; } <form accept-charset="UTF-8" method="p ...

After using JSON.parse(), backslashes are still present

Recently Updated: Received server data: var receivedData = { "files":[ { "filename": "29f96b40-cca8-11e2-9f83-1561fd356a40.png", "cdnUri":"https://abc.s3.amazonaws.com/" ...

Dynamic Menu Highlight Styling

I'm having trouble highlighting the current menu item when clicked using CSS. Here is the code I have: #sub-header ul li:hover{ background-color: #000;} #sub-header ul li:hover a{ color: #fff; } #sub-header ul li.active{ background-color: #000; } #su ...

Converting JSON to HTML without the use of external libraries

As a newcomer to JSON, I'm feeling quite puzzled by it. I need to transform a legitimate JSON string into a valid HTML string in order to display JSON on the web. jsonToHtml(“[{‘x’: 1, ‘b’: 2}, {‘x’: 100, ‘b’: 200}]") => “x:1x ...

Ways to connect a button to a Bootstrap 5 tab class

I am trying to find a way to directly link to a specific tab using a Bootstrap 5 button class. I have attempted to incorporate the solution provided in the following resource: Twitter Bootstrap 5 Tabs: Go to Specific Tab on Page Reload or Hyperlink Unfo ...

Restoring an object to its previous clean state in AngularJS

Is there a way to restore the original state of an object in AngularJS after it has been modified? In my scenario, I have an edit, save, and cancel buttons. When a user clicks on edit, the object's state changes, but if they then click cancel, I want ...