Interactive JavaScript Slider for Customizing Selection

Recently, I came across a range slider and I am trying to make it more dynamic. The current JavaScript code has hardcoded references to specific HTML elements, and I want to have multiple sliders on my HTML page, each functioning independently. The code snippet I am using can be found here: https://codepen.io/mukealicious/pen/jWoeZY (also provided below)

const $element = $('input[type="range"]');
const $tooltip = $('#range-tooltip');
const sliderStates = [
  {name: "low", tooltip: "Good.", range: _.range(80, 100) },
  {name: "med", tooltip: "Okay.", range: _.range(101, 149)},
  {name: "high", tooltip: "Bad.", range: [150] },
];
var currentState;
var $handle;

$element
  .rangeslider({
    polyfill: false,
    onInit: function() {
      $handle = $('.rangeslider__handle', this.$range);
      updateHandle($handle[0], this.value);
      updateState($handle[0], this.value);
    }
  })
  .on('input', function() {
    updateHandle($handle[0], this.value);
    checkState($handle[0], this.value);
  });

// Functions to update handle value and state based on slider input
function updateHandle(el, val) {
  el.textContent = Math.round(0.25*val) + "€";
}

function checkState(el, val) {
  if (!_.contains(currentState.range, parseInt(val))) {
    updateState(el, val);
  }
}

function updateState(el, val) {
  for (var j = 0; j < sliderStates.length; j++){
    if (_.contains(sliderStates[j].range, parseInt(val))) {
      currentState = sliderStates[j];
    }
  }

  if (currentState.name == "high") {
    updateHandle($handle[0], "150");
  }

  $handle
    .removeClass (function (index, css) {
    return (css.match (/(^|\s)js-\S+/g) ||   []).join(' ');
  })
    .addClass("js-" + currentState.name);

  $tooltip.html(currentState.tooltip);
}
/* CSS styling for the range slider */
/*...CSS code provided in the original text...*/
<!DOCTYPE html>
<html lang="en" >
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

</head>
<body>

<div class="main">
  <input
      type="range"
      name="participants"
      min="80"
      max="150"
      value="99"
      oninput="showVal(this.value)" 
      onchange="showVal(this.value)"
  >
  <span class="rangeslider__tooltip" id ="range-tooltip"></span>

<!-- Insert Additional Range Slider HTML Code Here -->

<script>
  function showVal(newVal){
       console.log("updated");
  </script>   

<!-- include necessary external scripts-->
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://andreruffert.github.io/rangeslider.js/assets/rangeslider.js/dist/rangeslider.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js'></script>

</body>
</html>

I've made several modifications to the JavaScript code, but I'm still encountering issues with changing the colors of the range sliders individually. If you have any helpful suggestions or hints, I would greatly appreciate it. Thank you.

Answer №1

The variable $element now contains multiple input elements, requiring an .each() loop to apply the function to each of them.

Therefore, I have enclosed the entire code within an .each() loop without any further modifications.


To handle tooltips, eliminate

const $tooltip = $("#range-tooltip");
from the global scope. Instead, utilize .siblings() method to target the appropriate tooltip span.

const $element = $('input[type="range"]');
const sliderStates = [
  { name: "low", tooltip: "Good.", range: _.range(80, 100) },
  { name: "med", tooltip: "Okay.", range: _.range(101, 149) },
  { name: "high", tooltip: "Bad.", range: [150] }
];

// Iterating over each input element
$element.each(function (index, element) {
  var currentState;
  var $handle;

  // Applying functionality on the element
  $(element)
    .rangeslider({
      polyfill: false,
      onInit: function () {
        $handle = $(".rangeslider__handle", this.$range);
        updateHandle($handle[0], this.value);
        updateState($handle[0], this.value);
      }
    })
    .on("input", function () {
      updateHandle($handle[0], this.value);
      checkState($handle[0], this.value);
    });

  // Updating the value inside the slider handle
  function updateHandle(el, val) {
    el.textContent = Math.round(0.25 * val) + "€";
  }

  // Checking if the slider state has changed
  function checkState(el, val) {
    // Update if the value does not fall within the range of the current state
    if (!_.contains(currentState.range, parseInt(val))) {
      updateState(el, val);
    }
  }

  // Changing the state of the slider
  function updateState(el, val) {
    for (var j = 0; j < sliderStates.length; j++) {
      if (_.contains(sliderStates[j].range, parseInt(val))) {
        currentState = sliderStates[j];
        // updateSlider();
      }
    }
    // If the state is high, update the handle count to read 50+
    if (currentState.name == "high") {
      updateHandle($handle[0], "150");
    }
    // Update handle color
    $handle
      .removeClass(function (index, css) {
          return (css.match(/(^|\s)js-\S+/g) || []).join(" ");
      })
      .addClass("js-" + currentState.name);
    // Update tooltip
    $(element).siblings(".rangeslider__tooltip").html(currentState.tooltip);
  }
});
label {
  display: block;
  margin-bottom: 2.5em;
  font-size: 13px;
  font-weight: bold;
}
/* CSS styles omitted for brevity */
<!DOCTYPE html>
<html lang="en" >
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

</head>
<body>

<div class="main">
  <input
      type="range"
      name="participants"
      min="80"
      max="150"
      value="99"
      oninput="showVal(this.value)" 
      onchange="showVal(this.value)"
  >
  <span class="rangeslider__tooltip" id="range-tooltip"></span>

<div class="main">
  <input
      type="range"
      name="participants"
      min="80"
      max="150"
      value="99"
      oninput="showVal(this.value)" 
      onchange="showVal(this.value)"
  >
  <span class="rangeslider__tooltip" id="range-tooltip"></span>

<script>
  function showVal(newVal){
    //console.log("updated");
  }
  </script>   

<!-- partial -->
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://andreruffert.github.io/rangeslider.js/assets/rangeslider.js/dist/rangeslider.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js'></script>

</body>
</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

What is the best way to pass props down to grandchildren components in React?

I'm trying to pass some props from a layout to its children. The issue is, it works fine when the child component is directly nested inside the layout, but it doesn't work when the child component is wrapped in another element like a div. Exampl ...

The dimensions of the box remain fixed and do not change when the screen is resized

Just starting out with HTML and CSS and trying to create a responsive website. Running into an issue where the black striped box on my page is not moving up when I resize the screen. It appears to be stuck in place, causing a gap between it and the slide s ...

Dynamic flexibility for content scrolling across components

Creating a mobile-friendly terms of service page with a title, content, and two buttons is my current project. The specific requirements are: All components should not exceed 100% of the viewport to allow for scrolling The buttons need to stay sticky at t ...

Navigate to the middle of the visible area

Is there a way to automatically center a div when it is clicked, so that it scrolls to the middle of the browser viewport? I have seen examples using anchor points but I want to find a different solution. Any ideas on how to accomplish this without using ...

Having trouble loading external CSS in HTML?

I have been attempting to load an external CSS file into my current HTML file without success. I have provided images showcasing the code: View the code here See the output here Currently, I am working on Windows and using Aptana Studio 3 as my IDE. ...

Positioning the close button on the top right edge of a Material-UI Dialog: A step-by-step guide

https://i.sstatic.net/ARTtq.png How can I include a close icon in the top right corner of the header section? I'm using the Material UI Dialog and everything works well, but I need a close button in the top section. Can anyone assist me with this? ...

let parsedObject = jQuery.parseJSON(response);

I'm working with a script that involves parsing JSON data received via AJAX. The script looks something like this: var obj = jQuery.parseJSON(response); The 'response' variable stores a JSON string with the following values: [ { ...

Setting constraints for table size with min-width and max-height

I have a coding dilemma involving the min-width and max-height properties in my table. The issue arises when I try to set these properties on the td element – they are being ignored by the browser. If I nest a div with the properties inside a td, the con ...

IE11 Experiencing Overflow Issue with List Item Pseudo Element Numbers

Having a simple unordered list of links and using pseudo elements to generate numbers for the list, I encountered an issue with centering the number vertically within its circle background in Internet Explorer 11. Here is the HTML code: <ul> < ...

AngularJS - Increase the input date by 6 hours before converting it to JSON

Is there a way to add 6 hours to an input date in AngularJS? I attempted the following code: var eventStart = new Date ($scope.event.startdateid); var startDate = new Date ( eventStart ); startDate.setHours ( eventStart.getHours() + 6 ); event.startdate ...

Ajax pagination does not update the currently active link

Hello, I am attempting to implement ajax pagination using CodeIgniter. However, I have encountered an issue where the active link in the pagination does not change. Can someone please assist me with this problem? Here is my AJAX code: $(function() { a ...

The response to ajax requests does not appear in Chrome Dev Tools

I'm experiencing an issue with my nodejs application where I encounter a peculiar situation when making ajax requests using jQuery. When I make a redirection in the callback function of the AJAX request, the response in the developer tools appears emp ...

Having trouble establishing a connection between the client and server while using Node.js with socket.io, Express, and an HTML file

While following a tutorial on YouTube for creating a simple web game with lobbies/rooms, I encountered an issue. When attempting to establish a connection between the client and server, the expected "a user connected" text did not show up in the console as ...

How to implement a cyclic item generation feature in React.js

My function is meant to draw multiple items in a cycle, but it is only drawing the first item when I attempt to draw 5. This is my function: export default function CinemaHole() { const items = []; for(let i = 0; i < 5; i++) { item ...

transferring a function from a main component to a nested component using swipeout functionality in react-native

I am attempting to transfer a function from a parent container to a child container within react native. The user is presented with a list of items on the screen, where they can swipe the list to reveal additional options. Child import React from &ap ...

Executing a npm script (script.js) with custom arguments - a step-by-step guide

I'm considering creating a setup similar to lodash custom builds. Basically, I want to allow users to input a command like: lodash category=collection,function This would create a custom module with the specified category. I've been looking in ...

Navigate Formik Fields on a Map

Material UI text-fields are being used and validated with Formik. I am looking for a way to map items to avoid repetitive typing, but encountering difficulties in doing so. return ( <div> <Formik initialValues={{ email: '&a ...

Choosing from a list in Angular

I'm trying to make a dropdown menu that shows options in the format "code-description", but only displays the "code" portion when an option is selected. For example, showing "A-Apple" in the dropdown, but displaying only "A" when chosen. I am able to ...

Embedding PHP script within HTML code can enhance website functionality and

I am completely new to PHP and have never worked with it before. I'm interested in running a PHP script from within an HTML file on a Linux system. Can anyone guide me through the process? Below is the code from my HTML file: <!DOCTYPE HTML PUBLI ...

Exploring the possibilities of maximizing, minimizing, resizing, and creating a responsive design in dialog boxes using jQuery UI JavaScript and

I'm trying to create a dialog with maximize, resize, and minimize buttons like those found in Windows OS. I want the dialog to be responsive and draggable as well. I've been using jQuery, jQuery UI, and extended dialog frameworks, but I haven&apo ...