Reputation: 23
I'm trying to have jQuery set the gradient background to be at a certain point on a range slider, but no matter what methods I try, it doesn't seem to want to work for me. I can get the log to show the correct percentage, but cannot get the style change to apply using the solution found here(how to call range::-webkit-slider-runnable-track?). Perhaps someone can spot what error I'm making along the way?
CSS styling:
background: linear-gradient(90deg, rgba(218,80,25,1) 0%, rgba(184,160,34,1) 1%);
function tTime(s) {
var h = Math.floor(s/3600);
s -= h*3600;
var m = Math.floor(s/60);
s -= m*60;
return (m < 10 ? m : m)+":"+(s < 10 ? '0'+s : s);
}
function diff(a,b){return Math.abs(a-b);}
function curr(s) {
var total = $("#progress-bar").prop('max');
var current = $("#progress-bar").val();
return ((100/total)*current);
}
var style = $("<style>", {type:"text/css"}).appendTo("head");
$(function() {
$('#elapsed').html( tTime($("#progress-bar").prop('min')) );
$('#remaining').html( tTime($("#progress-bar").prop('max')) );
$(document).on('input', '#progress-bar', function() {
$('#elapsed').html( tTime($(this).val()) );
$('#remaining').html( tTime(diff($("#progress-bar").prop('max'),$("#progress-bar").val())) );
var val = curr($(this).val());
style.text('input[type=range]::-webkit-slider-runnable-track { background-color: linear-gradient(90deg, rgba(218,80,25,1) 0%, rgba(184,160,34,1) ' + val + '%);}');
console.log(val + '%')
});
});
Upvotes: 2
Views: 142
Reputation: 15847
Modified from this answer, I was able to get it to work. It still uses a style tag, but it appends it to the head depending on which browser the user is using. It also checks to see if a style has already been created and removes it from the DOM.
function create_style(css) {
head = document.head,
oldstyles = head.querySelector("#rangestyle"),
style = document.createElement('style');
if (oldstyles != null) {
oldstyles.remove();
}
style.id = "rangestyle";
head.appendChild(style);
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}
create_style("input[type=range]::-webkit-slider-runnable-track { background: linear-gradient(90deg, rgba(218,80,25,1) 0%, rgba(184,160,34,1) 30%);}");
<input class="range" type="range" min="0" max="100" value="95" step="1" />
Upvotes: 1