JavaScript If/Else Function For Input Slider - javascript

I'm working on a an input slider which uses css translate for both "-" and "+" values using a JavaScript if/else function. I'm having a little problem with the if/else statement though.
Here's a fiddle http://jsfiddle.net/cn6St/ and here's the code:
HTML
<div class="square"></div>
<span class="result-X">Transform-X:</span>
<input type="range" id="sliderX" min="0" max="100" value="50" onchange="rangevalueX.value=value"/>
<output id="rangevalueX">50</output>
JS:
var sliderx = document.getElementById("sliderX");
var box = document.querySelector('.square');
var rangevalueX = document.getElementById("rangevalueX");
sliderx.onchange = function(){
if (rangevalueX >'50') {
box.style.webkitTransform = "translateX(" + (sliderx.value) + 'px)';
rangevalueX.value = sliderx.value;
}
else if (rangevalueX <'50') {
box.style.webkitTransform = "translateX(-" + (sliderx.value) + 'px)';
rangevalueX.value = sliderx.value;
}
};
The idea is to use the value of "50" on the slider as "0" in terms of translate. If the slider value is > 50 the CSS should transform a positive value. If it's less <50 it should be negative.
Not sure what I'm doing wrong here through.

You'll want to do:
var rangevalueX = document.getElementById('rangevalueX').value;
To get the actual slider value.

I Seem to have found the issue. It was the HMTL. The value of the slider should be set to "0", while the min should be "-50" and the max value should be "50".
Final working code:
HTML:
<div class="square"></div>
<div>
<span class="result-X">Transform-X:</span>
<input type="range" id="sliderX" min="-50" max="50" value="0" onchange="rangevalueX.value=value"/>
<output id="rangevalueX">0</output>
</div>
</div>
JavaScript:
var sliderx = document.getElementById("sliderX");
var box = document.querySelector('.square');
var rangevalueX = document.getElementById("rangevalueX");
sliderx.onchange = function(){
if (rangevalueX >'50') {
box.style.webkitTransform = "translateX(" + (sliderx.value) + 'px)';
rangevalueX.value = sliderx.value;
}
else if (rangevalueX <'50') {
box.style.webkitTransform = "translateX(-" + (sliderx.value) + 'px)';
rangevalueX.value = sliderx.value;
}
};
Working fiddle http://jsfiddle.net/cn6St/2/

Related

How to change the number on the slider in real time through javascript or CSS?

I would like to ask about the function that I made a slider that can display the value!
But I want to be able to swipe, and the numbers can change instantly, instead of stopping to display the numbers, how should this be rewritten?
I really need everyone's help, thank you in advance.
var slider = document.querySelector('#slider');
var result = document.querySelector('#result');
slider.addEventListener('change', function(event) {
var sliderValue = event.target.value;
var maxValue = 2000;
var coef = 18;
var calc;
calc = maxValue - (sliderValue * coef);
result.value = calc;
});
<input id="slider" type="range" name="points" min="0" max="100" value=0>
<input id="result" type="text" name="result">
Change your event listener from change to input.
var slider = document.querySelector('#slider');
var result = document.querySelector('#result');
slider.addEventListener('input', function(event) { //changed to input here
var sliderValue = event.target.value;
var maxValue = 2000;
var coef = 18;
var calc;
calc = maxValue - (sliderValue * coef);
result.value = calc;
});
<input id="slider" type="range" name="points" min="0" max="100" value=0>
<input id="result" type="text" name="result">

Getting Cm to ft values and displaying in other element gives reference error

I have the conversion math correct(looked it up here), but getting the value from the element that displays the height in cm, then parse it to ft/inch and display it on(on click) the right hand span does not work, i get a reference error(converter not defined).
I cannot figure out why it is undefined, is it because of hoisting or can the parseInt function not have the parameters as they are?
Here is the function
var displayInches = document.getElementById("heightInches");
displayInches.addEventListener("click", function() {
toFeet(converter);
});
function toFeet(converter) {
var heightOutputCM = document.getElementById("yourHeight");
var converter = parseInt(heightOutputCM.value);
var realFeet = converter * 0.3937 / 12;
var feet = Math.floor(realFeet);
var inches = Math.round((realFeet - feet) * 12);
return feet + "and" + inches;
}
Here is the link:
https://codepen.io/damianocel/pen/ZyRogX
HTML
<h1>Alcohol blood level calculator</h1>
<fieldset>
<legend>Your Indicators</legend><br>
<label for="height" class="margin">Height:</label>
<span class="leftlabel" id=""><span id="yourHeight"></span>Cm</span>
<input type="range" id="UserInputHeight" name="height" min="0" max="200" step="1" style="width: 200px">
<span id="heightInchesSpan" class="rightlabel"><span id="heightInches"></span>Ft</span>
<br>
<label for="" class="margin">Gender:</label>
<span class="leftlabel">Male</span>
<input type="range" id="salary" name="salary" min="0" max="1" style="width: 200px">
<span class="rightlabel">Female</span>
</fieldset>
JS
// get and display height
var displayHeightInput = document.getElementById("UserInputHeight");
displayHeightInput.addEventListener("input", function() {
sliderChange(this.value);
});
function sliderChange(val) {
var heightOutput = document.getElementById("yourHeight");
heightOutput.innerHTML = val;
toFeet();
return val;
}
function toFeet() {
var heightOutputCM = document.getElementById("yourHeight");
var converter = parseInt(heightOutputCM.innerHTML);
var realFeet = converter * 0.3937 / 12;
var feet = Math.floor(realFeet);
var inches = Math.round((realFeet - feet) * 12);
document.getElementById("heightInches").innerHTML=feet + "and" + inches;
return feet + " and " + inches;
}

display number 2 decimals

I have this code with 3 sliders that adds up all the 3 values of the sliders and displays it on the page, I want it to display it with 2 decimals after the comma. I tried using .toFixed(2) but I don't know where to place it exactly. Here is my code :
<div class="wrapper2">
<input class="slider" id="ram" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="10" data-slider-step="1" />
<hr />
<input class="slider" id="diskSpace" data-slider-id='ex1Slider2' type="text" data-slider-min="0" data-slider-max="100" data-slider-step="10" />
<hr />
<input class="slider" id="cpu" data-slider-id='ex1Slider3' type="text" data-slider-min="0" data-slider-max="4" data-slider-step="1" />
<hr />
<div id = "info"></div>
var minSliderValue = $("#ram").data("slider-min");
var maxSliderValue = $("#ram").data("slider-max");
$('#ram').slider({
value : 0,
formatter: function(value) {
return 'RAM: ' + value + 'GB';
}
});
$('#diskSpace').slider({
value : 0,
formatter: function(value) {
return 'Disk Space: ' + value + 'GB';
}
});
$('#cpu').slider({
value : 0,
formatter: function(value) {
return 'CPU : ' + value + ' Cores';
}
});
// If You want to change input text using slider handler
$('.slider').on('slide', function(slider){
var ram = $("#ram").val()*3.50;
var diskSpace = $("#diskSpace").val()*1.20;
var cpu = $("#cpu").val() * 6.30;
$("#info").html(parseInt(ram)+ parseInt(diskSpace)+ parseInt(cpu));
});
// If you want to change slider using input text
$("#inputValue").on("keyup", function() {
var val = Math.abs(parseInt(this.value, 10) || minSliderValue);
this.value = val > maxSliderValue ? maxSliderValue : val;
$('#ram','diskSpace','cpu').slider.toFixed(2)('setValue', val);
});
Jsfiddle: http://jsfiddle.net/4c2m3cup/34/
change your summing up code to the following
$('.slider').on('slide', function(slider){
var ram = $("#ram").val()*3.50;
var diskSpace = $("#diskSpace").val()*1.20;
var cpu = $("#cpu").val() * 6.30;
var totalSum=(parseFloat(ram)+ parseFloat(diskSpace)+ parseFloat(cpu)).toFixed(2);
$("#info").html(totalSum);
});
Hope it helps
You were parsing to an int. When you parse to int you lose the decimal places.
$("#info").html(parseInt(ram)+ parseInt(diskSpace)+ parseInt(cpu));
You can add them up and use x.toFixed(2). This will give you two decimal places just change the number as desired.
$("#info").html((ram + diskSpace + cpu).toFixed(2));

Why isn't this meter working?

So I have this code (Fiddle):
(function() {
var meter = document.getElementById('somemeter');
var Likes = document.getElementById('likes');
var Dislikes = document.getElementById('dislikes');
meter.max = Likes.innerHTML + Dislikes.innerHTML;
meter.value = Likes.innerHTML - Dislikes.innerHTML;
})();
<div id="likes">500</div>
<div id="dislikes">50</div>
<meter value="10" min="0" max="1000" id="somemeter"></meter>
As you can see, Likes.innerHTMLis 500 , and Dislikes.innerHTML is 50
For some reason, the meter.max doesn't work when I use Likes.innerHTML or Dislikes.innerHTML; however, when I substitute those in the meter.max for 500 and 50, it does work.
Am I doing something wrong?
Your code is taking the innerHTML as string. Use parseInt instead:
(function() {
var meter = document.getElementById('somemeter');
var Likes = document.getElementById('likes');
var Dislikes = document.getElementById('dislikes');
meter.max = parseInt(Likes.innerHTML, 10) + parseInt(Dislikes.innerHTML, 10);
meter.value = parseInt(Likes.innerHTML, 10) - parseInt(Dislikes.innerHTML, 10);
})();
<div id="likes">500</div>
<div id="dislikes">50</div>
<meter value="10" min="0" max="1000" id="somemeter"></meter>
Javascript detect string, you should use parseInt values, try this code:
(function() {
var meter = document.getElementById('somemeter');
var Likes = document.getElementById('likes');
var Dislikes = document.getElementById('dislikes');
meter.max = parseInt(Likes.innerHTML) + parseInt(Dislikes.innerHTML);
meter.value = parseInt(Likes.innerHTML) - parseInt(Dislikes.innerHTML);
console.log(meter.max)
})();
<div id="likes">500</div>
<div id="dislikes">50</div>
<meter value="10" min="0" max="1000" id="somemeter"></meter>
You need to convert the strings to numeric values for the math to work:
(function() {
var meter = document.getElementById('somemeter');
var Likes = document.getElementById('likes');
var Dislikes = document.getElementById('dislikes');
meter.max = Number(Likes.innerHTML) + Number(Dislikes.innerHTML);
meter.value = Number(Likes.innerHTML) - Number(Dislikes.innerHTML);
})();
Fiddle

How to restrict range slider in jQuery Mobile to a maximum value

I have a input type="range"in jquery mobile code. Based on some condition, I want to restrict the slider handle to go further after a certain limit ( but it can go backward )
For example, this is what I want to achieve in jQuery Mobile - http://jsfiddle.net/EL4tf/ ( Total is not exceeding 150 for all the three sliders )
The problem I am facing is that jQuery Mobile converts input type="range" into input type="number" therefore I am not able to put the condition event.preventDefault(); return false on $('.mySlider').bind('change') like they have put in the above fiddle example.
Any help will be appreciated!
From my comment, i prepared a simple solution which calculates the sliders total value and stops them increasing if greater than the total 150.
** Update from #ezanker. using the same process on change event. stops the slider in its tracks
Demo
http://jsfiddle.net/8jddyftc/
Jquery
var tota, totb, totc, alltot, altval, getslider;
var chktot = 150;
var scrore = 151;
//On Change event
$(document).on("change", "#range1, #range2, #range3", function (e) {
// Get the sliders Id
getslider = $(this).attr("id");
//Gather all slider values
tota = parseInt($("input#range1").val());
totb = parseInt($("input#range2").val());
totc = parseInt($("input#range3").val());
alltot = tota + totb + totc;
//check sliders total if greater than 150 and re-update slider
if (alltot > chktot) {
if (getslider == "range1") {
altval = chktot - totb - totc;
$("input#range1").val(altval).slider("refresh");;
}
if (getslider == "range2") {
altval = chktot - tota - totc;
$("input#range2").val(altval).slider("refresh");;
}
if (getslider == "range3") {
altval = chktot - tota - totb;
$("input#range3").val(altval).slider("refresh");;
}
}
//Update Total
if (alltot < scrore) {
$("#total").text(alltot);
}
})
If you want to limit the slider already during dragging, you can modify the CSS of the <a> component that is used to render the slider.
Demo: http://jsfiddle.net/ukaxkej0/2/
Try yourself: the slider will not move further if the sum is already at its limit.
To change the CSS:
var MAX = 150; // maximum allowed sum
var DEFAULT = 50; // slider default
var SMAX = 100; // slider max
var old1=DEFAULT, old2=DEFAULT, old1=DEFAULT;
// sliders trigger number changes; prevent them if sum exceeds maximum
$("input[type='number']").change(function(e){
var val1 = $("#range1").val();
var val2 = $("#range2").val();
var val3 = $("#range3").val();
var sum = parseInt(val1) + parseInt(val2) + parseInt(val3);
if (sum <= MAX) {
$("#total").text(sum);
old1=val1;
old2=val2;
old3=val3;
}
else {
if (val1 != old1) {
$("#range1").val(old1);
$("a[aria-labelledby='range1-label']").css('left', (100*old1/SMAX)+'%');
}
if (val2 != old2) {
$("#range2").val(old2);
$("a[aria-labelledby='range2-label']").css('left', (100*old2/SMAX)+'%');
}
if (val3 != old3) {
$("#range3").val(old3);
$("a[aria-labelledby='range3-label']").css('left', (100*old3/SMAX)+'%');
}
}
});
In addition, you have to prevent slider interaction if the sum exceeds the maximum.
$('.ui-slider-handle').mousemove(function(e){
var val1 = $("#range1").val();
var val2 = $("#range2").val();
var val3 = $("#range3").val();
var sum = parseInt(val1) + parseInt(val2) + parseInt(val3);
if (sum > MAX) {
e.preventDefault();
return false;
}
return true;
});
HTML (as suggested by Tasos):
<div data-role="page">
<input id="range1" type="range" min="0" max="100" value="50" />
<input id="range2" type="range" min="0" max="100" value="50" />
<input id="range3" type="range" min="0" max="100" value="50" />
<div>total: <strong id="total">0</strong>/150</div>
</div>

Categories