$(() => {
// call setup slider passing in values
setupSlider('mySlider4', ["1H", "1D", "1W", "1M", "1Y", "ALL"], 2);
});
// setup slider HTML, then call the following method with the values
function setupSlider(id, vals, initialVal = 0) {
$(`#${id}`).append($('<div>').addClass('step-marks'));
$(`#${id}`).append($('<div>').addClass('step-labels'));
$(`#${id}`).append($('<input type="range">'));
const min = 0;
const max = vals.length - 1;
// initialise slider vals
$(`#${id} input[type=range]`)
.attr({ min: min, max: max })
.val(initialVal);
vals.forEach((x, i) => {
if (i < vals.length - 1) {
$(`#${id} .step-marks`).append($("<div>"));
}
const label = $("<span>").text(x).on('click', () => $(`#${id} input[type=range]`).val(i));
$(`#${id} .step-labels`).append(label);
});
const length = vals.length;
const multiply = length / (length - 1);
const widthVal = `calc(100% * ${multiply} - 25px)`;
const marginVal = `calc(${widthVal} / ${length * -2} + 10px)`;
$(`#${id} .step-labels`).css("width", widthVal);
$(`#${id} .step-labels`).css("margin-left", marginVal);
$(`#${id}`).show();
}
.sliderWithLabels {
width:100%;
padding: 20px 40px 0;
height: 80px;
overflow: hidden;
display: none;
}
.sliderWithLabels input[type=range] {
position: relative;
height: 0.5rem;
margin-top: 1.25rem;
margin-bottom: 2.25rem;
background-color: #e6e6e6;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-ms-touch-action: none;
touch-action: none;
top: -49px;
position: relative;
-webkit-appearance: none;
width: 100%;
height: 10px;
background: #d3d3d3;
outline: none;
border-radius: 10px;
}
.sliderWithLabels input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 20px;
height: 20px;
background: #4087c7;
cursor: pointer;
border-radius: 100%;
}
.sliderWithLabels input[type=range]::-moz-range-thumb {
width: 20px;
height: 20px;
background: #4087c7;
cursor: pointer;
}
.sliderWithLabels > div {
display: flex;
align-items: stretch;
height: 20px;
margin-top: -6px;
position: relative;
width: 100%;
}
.sliderWithLabels > div > div {
color: white;
width: 100px;
margin: 0px;
text-align: center;
line-height: 75px;
font-size: 30px;
flex: 1;
border-right: 1px solid #d3d3d3;
border-left: 1px solid #d3d3d3;
}
.sliderWithLabels > div > div:first-of-type {
border-left: 2px solid #fff;
}
.sliderWithLabels > div > div:last-of-type {
border-right: 2px solid #fff;
}
.sliderWithLabels > div > span {
color: #444;
margin: 0px;
text-align: center;
line-height: 75px;
font-size: 15px;
flex: 1;
font-family: sans-serif;
}
.sliderWithLabels > div.step-labels {
top: -10px;
}
.sliderWithLabels > div.step-labels span {
cursor: pointer;
}
.sliderWithLabels > div.step-marks {
width: calc(100% - 20px) !important;
margin-left: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="width:50%">
<div class="sliderWithLabels" id="mySlider4"></div>
</div>