This is a premium alert message you can set from Layout! Get Now!

Creating a custom CSS range slider with JavaScript upgrades

0

Range sliders are an awesome tool for letting users select a value or filter items based on numeric ranges. They’re often used by developers to create progress bars, volume controls in audio and video players, product filters on ecommerce websites, and even for zooming features.

But adding a slider widget to a web page can be trickier than you might think. Sure, you can simply use an <input /> element of type range, but styling it consistently across different browsers can be a real headache.

That’s why we’ve put together this guide to show you how to create a custom range slider using CSS only. If you’re feeling adventurous, we’ll even show you how to take it to the next level with JavaScript.

We will cover:

Here is the final project:

See the Pen Custom CSS range slider by Ibadehin Mojeed (@ibaslogic)
on CodePen.

You can interact with it, and after that, get started!

Understanding the HTML range input type

In its simplest form, an input element of type range will look like this:

<input type="range"/>

This code will result in a widget that is inconsistent across browsers, as we can see below:

Html Range Input Type Inconsistencies Across Chrome, Firefox, Edge, And Safari Browsers

These irregularities call for customization if we want the slider widget to fit a particular theme or brand.

Why is the input range tricky to style?

As you can see in the image below, a range slider widget consists of certain key elements — a thumb (label 1) and a slider track (label 2) contained within a container input element (label 3, shown in gray):

Input Range Example With Three Numbered Labels Indicating Different Components. Label One Indicates Slider Thumb, Label Two Indicates Slider Track, and Label Three Indicates Container Input Element

To customize this slider widget, we only need to target the different components. However, inspecting the widget from the browser’s developer tools shows that the components are not exposed to us:

Range Input Type As Shown When Inspecting Widget From Browser Developer Tools With No Exposed Components

In the image above, we see only the rendered <input /> and not those elements responsible for the slider track and the thumb.

This is because the range element is implemented as a web component. Browsers internally encapsulate and hide elements and styles that make up the input slider inside a shadow DOM.

If you’re on Chrome, you can enable the Show user agent shadow DOM option from Settings to see the shadow DOM:

Chrome Developer Tools With Shadow Dom View Enabled To Show Range Input Type Sub Component Elements

In the shadow DOM, as seen above, we can see the sub-component elements in a structured manner.

This shadow DOM helps isolate components — in our case, the input range — from the actual DOM, including their styles. Doing so prevents those isolated components from conflicting with the styles of other elements in the real DOM.

For instance, targeting the thumb component using its ID from our CSS file will not affect the thumb appearance:

#thumb {
  color: red;
}

This implementation is beneficial because we can use web components without worrying about style conflicts from the hosting document. However, the inconsistencies between how the different browsers implement those web components make them tricky to style.

Creating a custom range slider with CSS only

Let’s create a range slider that looks like the below with a CSS-only solution:

See the Pen Custom CSS range slider by Ibadehin Mojeed (@ibaslogic)
on CodePen.

As we mentioned earlier, we’ll target the different slider parts to add a custom style. Since we don’t have access to the parts directly, we’ll capitalize on the various browser vendor prefixes.

For instance, to customize the range slider for the WebKit and Blink-based browsers — like Safari, Chrome, Opera, and Edge — we’ll use the ::-webkit-slider-runnable-track pseudo-element to target the slider track and the ::-webkit-slider-thumb pseudo-element to target the thumb.

For Mozilla Firefox, we’ll use ::-moz-range-track pseudo-element to target the track and ::-moz-range-thumb for the thumb.

Now that we know which CSS pseudo-elements to use, let’s start by adding the base styles.

Adding the base styles

We’ll start by removing the default styles of the native range input and then adding custom styles:

input[type="range"] {
  /* removing default appearance */
  -webkit-appearance: none;
  appearance: none;
  /* creating a custom design */
  width: 100%;
  cursor: pointer;
  outline: none;
}

The range input’s appearance property tells the browser to remove the default appearance styles so that we can apply a custom style.

Setting the -webkit-appearance property to none; on the container element only removes the track and not the thumb:

Chrome Range Input Type Before And After Appearance Property Is Set To None

The above is what it looks like in Chrome. The other WebKit-based browsers will also remove the track bar only.

However, Mozilla does not only remove the track; it also eliminates some default appearances from the thumb:

Mozilla Range Input Type Before And After Appearance Property Is Set To None

Let’s move on to customizing the track and slider thumb.

Customizing the track

We can style the slider track in two ways. The first method is applying the custom styles directly in the input[type="range"] selector:

input[type="range"] {
  /* ... */

  /*  styling the track  */
  height: 15px;
  background: #ccc;
  border-radius: 16px;
}

With this method, we don’t have to target the track component specifically. The input container element takes the slider role.

However, for this project, we’ll go with the next approach — using the browser’s vendor prefixes to specifically target the slider track. So, let’s remove the just-added style declarations.

As we mentioned above, the ::-webkit-slider-runnable-track pseudo-element will target the slider track for WebKit-based browsers. Meanwhile, the ::-moz-range-track pseudo-element will target the track for Mozilla Firefox:

/* Track: webkit browsers */
input[type="range"]::-webkit-slider-runnable-track {
  height: 15px;
  background: #ccc;
  border-radius: 16px;
}

/* Track: Mozilla Firefox */
input[type="range"]::-moz-range-track {
  height: 15px;
  background: #ccc;
  border-radius: 16px;
}

The range slider should now look like so:

Range Slider Resulting From Using Browser's Vendor Prefixes To Target Slider Track

Customizing the slider thumb

For WebKit-based browsers, we’ll start by removing the default styles of the native slider thumb and then adding custom styles:

/* Thumb: webkit */
input[type="range"]::-webkit-slider-thumb {
  /* removing default appearance */
  -webkit-appearance: none;
  appearance: none;
  /* creating a custom design */
  height: 15px;
  width: 15px;
  background-color: #fff;
  border-radius: 50%;
  border: 2px solid #f50;
}

For Mozilla Firefox, we’ll only apply the custom styles:

/* Thumb: Firefox */
input[type="range"]::-moz-range-thumb {
  height: 15px;
  width: 15px;
  background-color: #fff;
  border-radius: 50%;
  border: 1px solid #f50;
}

Due to how Mozilla handles the thumb, we reduced the border from the 2px applied for WebKit browsers to 1px so the thumb can fit appropriately in the range slider.

Keep in mind that Mozilla applies a grey border to the thumb by default. You can add a border: none; property if you don’t want to apply a border.

The slider should now look like so:

Customizing Range Slider Thumb Styles And Adjusting Border Property

As we can see, both the slider track and thumb have rounded shapes. If you want to make the shape rectangular, you can remove the border-radius CSS property from the components:

input[type="range"]::-webkit-slider-runnable-track {
 /* border-radius: 16px; */
}

/* Track: Mozilla Firefox */
input[type="range"]::-moz-range-track {
 /* border-radius: 16px; */
}

input[type="range"]::-webkit-slider-thumb {
 /* border-radius: 50%; */
}

input[type="range"]::-moz-range-thumb {
 /* border-radius: 50%; */
}

Styling the range slider to show track progress

With CSS only, we can style the range slider to show track progress by filling the space to the left of the thumb with box-shadow and then hiding the overflow from the input[type="range"] selector.

Let’s locate the ::-webkit-slider-thumb and ::-moz-range-thumb pseudo-elements and then add the following box-shadow declaration:

/* Thumb: webkit */
input[type="range"]::-webkit-slider-thumb {
  /*  ...  */
  /*  slider progress trick  */
  box-shadow: -407px 0 0 400px #f50;
}

/* Thumb: Firefox */
input[type="range"]::-moz-range-thumb {
  /*  ...  */
  /*  slider progress trick  */
  box-shadow: -407px 0 0 400px #f50;
}

After that, in the input[type="range"] selector, let’s add the following declarations:

input[type="range"] {
  /*  ...  */
  /*  slider progress trick  */
  overflow: hidden;
  border-radius: 16px;
}

The styled slider should now behave like the first example in the GIF below:

Styled Range Slider Showing Track Progress

How to improve the CSS range slider with JavaScript

With the addition of JavaScript, we’ll create a range slider that looks like so:

See the Pen Custom CSS range slider by Ibadehin Mojeed (@ibaslogic)
on CodePen.

Due to the overflow: hidden and box-shadow tricks we used to customize the slider progress with the CSS-only solution, the slider thumb cannot be larger than the track, the way it’s shown below:

Styled Slider Thumb Displaying Larger Than Track Size Using Javascript

To achieve the above design, we’ll modify the CSS style rules and apply a bit of JavaScript.

On the input[type="range"] selector, let’s remove the overflow: hidden declaration and then set a height and background color properties:

input[type="range"] {
  /* removing default appearance */
  -webkit-appearance: none;
  appearance: none;
  /* creating a custom design */
  width: 100%;
  cursor: pointer;
  outline: none;
  border-radius: 15px;
  /*  overflow: hidden;  remove this line*/

  /* New additions */
  height: 6px;
  background: #ccc;
}

With the height and background color on the input element, we don’t need to specifically target the track component.

So, we can remove the pseudo-elements that we used earlier to target the track lines for each browser’s vendors:

// input[type="range"]::-webkit-slider-runnable-track {}
// input[type="range"]::-moz-range-track {}

For the slider thumb, we’ll remove the box-shadow declaration that we added in the CSS-only solution:

/* Thumb: webkit */
input[type="range"]::-webkit-slider-thumb {
  /* removing default appearance */
  -webkit-appearance: none;
  appearance: none;
  /* creating a custom design */
  height: 15px;
  width: 15px;
  background-color: #f50;
  border-radius: 50%;
  border: none;

  /* box-shadow: -407px 0 0 400px #f50; emove this line */
  transition: .2s ease-in-out;
}

/* Thumb: Firefox */
input[type="range"]::-moz-range-thumb {
  height: 15px;
  width: 15px;
  background-color: #f50;
  border-radius: 50%;
  border: none;

  /* box-shadow: -407px 0 0 400px #f50; emove this line */
  transition: .2s ease-in-out;
}

Notice we added a CSS transition property for a smooth transition effect. We’ll see the effect when we implement the hover, active, and focus states for the slider thumb.

Adding hover, active, and focus states

For the sake of accessibility and a positive UX, we’ll add styles for focus, hover, and active states to provide a visual effect while interacting with the slider.

If you take a look at the input[type="range"] selector, we applied the CSS outline: none; property to remove the default focus styles. We can now target the slider thumb using the pseudo-elements, then use the :focus, :hover, and :active pseudo-classes on them to provide a custom style:

/* Hover, active & focus Thumb: Webkit */

input[type="range"]::-webkit-slider-thumb:hover {
  box-shadow: 0 0 0 10px rgba(255,85,0, .1)
}
input[type="range"]:active::-webkit-slider-thumb {
  box-shadow: 0 0 0 13px rgba(255,85,0, .2)
}
input[type="range"]:focus::-webkit-slider-thumb {
  box-shadow: 0 0 0 13px rgba(255,85,0, .2)
}

/* Hover, active & focus Thumb: Firfox */

input[type="range"]::-moz-range-thumb:hover {
  box-shadow: 0 0 0 10px rgba(255,85,0, .1)
}
input[type="range"]:active::-moz-range-thumb {
  box-shadow: 0 0 0 13px rgba(255,85,0, .2)
}
input[type="range"]:focus::-moz-range-thumb {
  box-shadow: 0 0 0 13px rgba(255,85,0, .2)   
}

The second example in the GIF below demonstrates how the slider should behave with the custom styling we just added:

Demo Of Styled Thumb Using Javascript

Adding JavaScript to style the range slider progress

We’ll start with a quick way of adding the slider progress. Let’s add an id attribute to the input element so that we can reference it with JavaScript:

<input type="range" id="range" oninput="progressScript()" /> 

We also added an oninput attribute in the HTML that’ll trigger an event when the user drags the range slider.

In JavaScript, we’ll create the progressScript() function to handle the input event:

const sliderEl = document.querySelector("#range")

function progressScript() {
  const sliderValue = sliderEl.value;
  sliderEl.style.background = `linear-gradient(to right, #f50 ${sliderValue}%, #ccc ${sliderValue}%)`;
}

progressScript()

We achieved the progress style effect with the code by applying a linear-gradient to the background of the runnable track.

The result now looks like so:

Custom Larger Thumb With Styled Progress Indicator

By default, the range input has a minimum and maximum value of 0 and 100, respectively. We can specify a min and max attributes to change the default.

Let’s change the default while also displaying the input value as we interact with the widget. We’ll update the HTML to include the min, max, and value attributes:

<input type="range" min="0" max="50" value="0" id="range" /> 
<div class="value">0</div>

Then, we’ll target these elements in JavaScript and dynamically update the display value and slider progress when the user drags the range slider:

const sliderEl = document.querySelector("#range")
const sliderValue = document.querySelector(".value")

sliderEl.addEventListener("input", (event) => {
  const tempSliderValue = event.target.value;
  sliderValue.textContent = tempSliderValue;

  const progress = (tempSliderValue / sliderEl.max) * 100;

  sliderEl.style.background = `linear-gradient(to right, #f50 ${progress}%, #ccc ${progress}%)`;
})

We used the addEventListener() method in the code to handle the input event. The result now looks like so:

Demo Of Input Event Used To Show Progress Bar Value

As we can see, the progress bar is always in sync with the max attribute of the input range. We can also customize the thumb to have a rectangular shape by removing the border-radius property:

input[type="range"]::-webkit-slider-thumb {
  /* ... */
  height: 30px;
  width: 15px;
  /* border-radius: 50%; */
}

The above style rule also modifies the height property to achieve the following result:

Modified Thumb With Rectangular Shape And Updated Height

Applying a custom image to our slider control

Let’s get more creative and create a slider control using emoji or custom image as the thumb, like so:

See the Pen Custom CSS range slider by Ibadehin Mojeed (@ibaslogic)
on CodePen.

On top of the last slider example, we’ll replace the background color that we applied on the thumb with a background image so that the thumb becomes an image rather than a colored circle:

/* Thumb: webkit */
input[type="range"]::-webkit-slider-thumb {
  /* ... */
  height: 30px;
  width: 30px;
  /* background-color: #f50; remove this*/
  background-image: url("https://ibaslogic.github.io/hosted-assets/smile.png");
  background-size: cover;
}

/* Thumb: Firefox */
input[type="range"]::-moz-range-thumb {
  /* ... */
  height: 30px;
  width: 30px;
  /* background-color: #f50; */
  background-image: url("https://ibaslogic.github.io/hosted-assets/smile.png");
  background-size: cover;
}

We’ve also increased the thumb size via the height and width properties. Furthermore, notice that we included a background-size property. Without this property, we won’t be able to see the thumb image.

Rotating the thumb emoji

To make the thumb rotate when we drag it, we will apply a transform property on it like so:

/* Thumb: webkit */
input[type="range"]::-webkit-slider-thumb {
  /* ... */
  /* rotate thumb */
  transform: rotateZ(var(--thumb-rotate, 0deg));
}

/* Thumb: Firefox */
input[type="range"]::-moz-range-thumb {
  /* ... */
  /* rotate thumb */
  transform: rotateZ(var(--thumb-rotate, 0deg));
}

In the style rule, we used a CSS variable so we can dynamically update the amount of rotation. Let’s grab the CSS variable in our JavaScript file and update it based on the slider progress to get the angle of rotation:

sliderEl.addEventListener("input", (event) => {
  // ...
  sliderEl.style.setProperty("--thumb-rotate", `${(tempSliderValue/100) * 2160}deg`)
})

The widget should now behave like so:

Custom Emoji Thumb With Rotation Animation

Conclusion

Creating a custom range slider that looks great and works seamlessly on any browser without sacrificing accessibility can be daunting.

This guide walked you through how to customize a range slider using CSS only, ensuring a consistent look and feel across browsers. We also showed how to enhance this slider widget with JavaScript if you want to take it up a notch.

But wait, there’s more! We’ve even created an audio player guide that demonstrates how you can use this slider to create a progress bar and volume control in your projects.

Have questions or suggestions? Share them in the comments section below. And if you found this guide helpful, don’t forget to spread the word!

The post Creating a custom CSS range slider with JavaScript upgrades appeared first on LogRocket Blog.



from LogRocket Blog https://ift.tt/zJNnRhI
Gain $200 in a week
via Read more

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment

Search This Blog

To Top