Skip to content
Advertisement

Add css class to noUiSlider handle on event

By default on the start event noUiSlider adds an active class to the active handle but removes it when the event has ended. I want a way to show the user that the handle has been dragged already so changing the colour via a css class would be ideal.

I cannot tell which of the handles has been dragged from the data it provides.

Here is my function which initiates noUISlider

setRangeSlider(e) {
  const min = 0;
  const max = 1000000;
  noUiSlider.cssClasses.target += ' c-range-slider';
  const options = {
    start: [min || 0, max || this.maxAvailablePrice.id],
    step: 50000,
    tooltips: true,
    connect: true,
    range: {
      min,
      max,
    },
    format: {
      to(value) {
        return formatCurrency([value]);
      },
      from(value) {
        return stripFormatting(value);
      },
    },
  };
  this.slider = noUiSlider.create(e, options);

  this.slider.on('start', (values) => {
    console.log('SearchFiltersPriceComponent -> setRangeSlider -> this.slider', this.slider);
  });
}

When I console out this.slider from the start event it prints out all sorts of useful information but I cannot find which handle has just been dragged and how to target that handle to add a class to it.

Advertisement

Answer

this.slider.target will return the slider element and handle parameter in event callback function will return the index of the handle that has been dragged. so these two can be used together to locate a particular handle. see the code for example

setRangeSlider(e) {
  const min = 0;
  const max = 1000000;
  noUiSlider.cssClasses.target += ' c-range-slider';
  const options = {
    start: [min || 0, max || this.maxAvailablePrice.id],
    step: 50000,
    tooltips: true,
    connect: true,
    range: {
      min,
      max,
    },
    format: {
      to(value) {
        return formatCurrency([value]);
      },
      from(value) {
        return stripFormatting(value);
      },
    },
  };
  this.slider = noUiSlider.create(e, options);

  this.slider.on('start', (values, handle, unencoded, tap, positions, noUiSlider) => {
    let sliderElem = this.slider.target;
    let handleElem = document.querySelectorAll("div.noUi-handle[data-handle='" + handle + "']")[0];
    console.log('SearchFiltersPriceComponent -> setRangeSlider -> this.slider', handleElem);
     handleElem.classList.add("mystyle");
  });

  this.slider.on('end', (values, handle, unencoded, tap, positions, noUiSlider) => {
    let sliderElem = this.slider.target;
    let handleElem = document.querySelectorAll("div.noUi-handle[data-handle='"+handle+"']")[0];
    handleElem.classList.remove("mystyle");
   });
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement