How to be able to use HTML slider with arrow keys - javascript

I have this code written up to and the issue I am having is moving the slider with arrow keys, it works if I first click the slider but I want it to work on the page load without having to click the slider first and am not sure how to accomplish that.
<script>
function updateImage(sliderValue) {
document.getElementById("image").src =
"img"
+ sliderValue + ".png";
}
document.getElementById('slider').addEventListener(function() {
this.focus();
});
</script>
<div class="slider-container">
<input type="range" min="0" max="384" value="0" step="6"
oninput="updateImage(this.value)" id="slider"/>
</div>
<img id="image" src="img.png" width="1144" height="898">

Add a keydown listener on the document that checks the event key code (from which it determines the key pressed), and changes the slider value accordingly:
document.addEventListener('keydown', function(e) {
if (e.keyCode == 39) { //right
slider.value = +slider.value + +slider.step;
} else if (e.keyCode == 37) { //left
slider.value = +slider.value - +slider.step;
}
updateImage(slider.value)
})
function updateImage(sliderValue) {
console.log(sliderValue)
document.getElementById("image").src =
"img" +
sliderValue + ".png";
}
<div class="slider-container">
<input type="range" min="0" max="400" value="384" step="6" id="slider" oninput="updateImage(this.value)" />
</div>
<img id="image" src="img.png">

The first thing, you can do your job with two different ways, one is simple and not entirely active, and the second is great but more complicated:
The First way:
You can add a onload event for the window, and when the window is loaded you can focus on the slider input, and this will makes it possible to use arrow keys for move your slides right and left.
and instead of saying:
document.getElementById('slider').addEventListener(function() {
this.focus();
});
You can say that:
window.onload = function() {
document.getElementById("slider").focus()
}
And this will put the focus on your input directly when the window is finishes loading.
This is the easy way to use arrow buttons to navigate your slider,
But there is another advanced way to do this.
The Second way:
You can use the keyEvents on the window itself again but not for pushing the focus to the input range, you will use it for getting what's clicked whatever where, and if the clicked button is one of the arrow left or right buttons, increase or decrease the value of the slider, and run the updateImage with the new value
and this is the code that you need to put after the updateImage function:
window.addEventListener("keydown", (e) => {
let slider = document.getElementById("slider")
if( e.key === "ArrowLeft" ) {
e.preventDefault()
slider.value -= 1
updateImage(slider.value)
}
else if( e.key === "ArrowRight" ) {
e.preventDefault()
slider.value = Number(slider.value) + 1
updateImage(slider.value)
}
})
Here in this code, you will find that I apply the function whenever a keydown event happens in the window, whatever where.
And inside the function, I got the slider, then check for the arrow left and right keys, inside the two condition I prevent default actions of the buttons, but you can delete this part, then I increase or decrease the slider value by one, "In your case add or remove 6, because you set the step to 6",
then I updateImage mySelf with the new value, and that's because changing the input value from javascript will not run your oninput event attached to the input.
And now, you can click on the right and left arrows while you are not even focus on the input, and the images will still changed and the slider itself will still changed.
I hope I managed to solve your problem.

My solution of your problem.
const slider = document.getElementById('slider');
slider.addEventListener(e => {
switch(e.key) {
case "ArrowLeft":
// Left arrow logic
break;
case "ArrowRight":
// Right arrow logic
break;
}
});

Related

Increment input value using mouse wheel

I'm trying to increase/decrease the value of input field using mouse wheel. I've put together the following code. It's working fine, but there's a small problem.
The behaviour I want is to be able to increment/decrement the input value using mouse wheel once I focus on the element. Mouse doesn't have to be hovering the element. The following code performs this. But if I use wheel while hovering the input element, the value is incremented/decremented by 2 instead of 1.
var hoveredInput = null;
$('input[type="number"]').on("focus", function(e) {
hoveredInput = this;
});
$('input[type="number"]').on("blur", function(e) {
hoveredInput = null;
});
$(window).on("wheel", function(e) {
if (hoveredInput) {
if (e.originalEvent.deltaY < 0) {
var currentValue = parseInt(hoveredInput.value, 10);
var newValue = currentValue + 1;
if (newValue > parseInt(hoveredInput.max, 10)) {
newValue = hoveredInput.max;
}
hoveredInput.value = newValue;
} else {
var currentValue = parseInt(hoveredInput.value, 10);
var newValue = currentValue - 1;
if (newValue < parseInt(hoveredInput.min, 10)) {
newValue = hoveredInput.min;
}
hoveredInput.value = newValue;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="0" min="0" max="255" />
After some experimenting, I figured that there's a similar behaviour for up and down arrow keys. Up and down arrow keys, on a number input, increments/decrements the value. And I suppose, this behaviour conflicts with my code. Causes it to increment by 2, even though the code doesn't execute twice.
I've just realized that this might be a Chrome specific problem. Chrome let's you increment/decrement number input value using mouse wheel if you focus and hover the element. However, it works in a really weird way.
If I just add <input type="number" /> in a blank HTML page, this mouse wheel increment doesn't work. To make it work, I simply add window.onwheel = function() {};. This doesn't make any sense. Also this seems to work on JSFiddle and JSBin without onwheel assignment on the window.
Going back to the actual problem, can I disable the default mouse wheel increment on the element, so that I can use my custom one? Or is there another approach that I can use?
I'm not sure why you would be considering not using preventDefault() to prevent the default action. You are changing what the UI action will be under these circumstances. You should, of course, use preventDefault() to prevent the default action. If you don't use preventDefault() then there would be some unexpected consequences to using the scroll wheel when the <input type="number"> is focused. Without preventDefault(), what combination of unexpected consequences would occur under those conditions will depend on the browser that is being used to view the page.
I am unable to duplicate a conflict with using the cursor keys to change the input value. Obviously, if all you are using to limit the minimum and maximum values of the <input> is the code for the mouse wheel, then those limits will not function for any other method of entry. You could use the min and max attributes for limiting values. Doing so would be better for multiple reasons, including that it affects all methods of entering a value and as it allows defining those ranges per <input> instead of one set of limits for all <input type="number">. I have changed the code so that your code also uses these attributes.
If you do this, you may want to consider adding a CSS style to indicate that the <input type="number"> element has focus. Doing so will make it more clear to the user why the mouse wheel is not doing what they normally expect from their browser's UI.
I suggest you try this with multiple browsers to see if it is something you desire. Personally, at least in the testing I have done on this page, I like the behavior.
NOTE:
Your use of the focus and blur events is overly complex. I have changed the code to directly find the focused element using document.activeElement.
//Exclude one specific element for comparing this UI vs. the browser's default.
var excludedEl = document.getElementById('exclude');
$(window).on("wheel", function(e) {
focusedEl = document.activeElement;
if(focusedEl === excludedEl){
//Exclude one specific element for UI comparison
return;
}
if (focusedEl.nodeName='input' && focusedEl.type && focusedEl.type.match(/number/i)){
e.preventDefault();
var max=null;
var min=null;
if(focusedEl.hasAttribute('max')){
max = focusedEl.getAttribute('max');
}
if(focusedEl.hasAttribute('min')){
min = focusedEl.getAttribute('min');
}
var value = parseInt(focusedEl.value, 10);
if (e.originalEvent.deltaY < 0) {
value++;
if (max !== null && value > max) {
value = max;
}
} else {
value--;
if (min !== null && value < min) {
value = min;
}
}
focusedEl.value = value;
}
});
input[type="number"]:focus {
box-shadow: 0px 0px 1.5px 1px cyan;
}
/*For comparing UIs: May conflict with browser default, or user's theme.*/
#exclude:focus {
box-shadow: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
NOTE: Events are only caught while the mouse stays within the test portion of the stackoverflow page:<br/><br/><br/>
Uses changed UI (if focused, mouse wheel will increment/decrement):<br/>
<input type="number" value="0" id="firstNumberInput" min="0" max="255"/>
<br/>Uses browser default UI:
<input id="exclude" type="number" value="0" min="0" max="255" style="display:block"/>

How to change HTML range slider value with button?

I am using a HTML range slider to zoom in and zoom out an image. I also want to show two buttons with slider like + for zoom and − for zoom out. When a user clicks on either of these buttons, the slider should also be moved. But I am unable to do this. Here is my code.
<div id="slider">
<input id="slide" type="range" min="330" max="1200" step="30" value="330" onchange="ImageViewer.sliderAction(this.value)" />
</div>
Here is my function:
var sliderAction = function (value) {
$sliderChosen.html(value);
$("#img").width(value);
$("#img").height(value);
};
When I click the button, I tried this:
btnZoomIn.click(function() {
$("#slide").value(); //Want to change value but value is undefined.
});
Is there any way to change slider value and move it as well on button click?
use val()
btnZoomIn.click(function() {
//if value < max
$("#slide").val(parseInt($("#slide").val())+30);
$("#slide").trigger('change');
});
https://jsfiddle.net/9jfst447/
You can use callback function of .val() and then trigger onchange event:
var sliderelement = $( "#slide" );
btnZoomIn.click(function() {
sliderelement.val(function( index, value ) {
return parseInt(value,10) + 30;
});
sliderelement[0].onchange()
});

Backspace not working correctly

I have built a calculator where a user can either click on the buttons or s/he can select the variables from the drop down. Insertion using keyboard is denied. Now when I click on the highlighted back arrow button which has been put for backspace functionality, only the character present at the right most position is deleted even if my cursor is placed in between the expression using mouse. Is there a workaround to remove the character right before the position where I place my cursor? I am using the below condition on left arrow click:
formulaText.value = formulaText.value.slice(0, formulaText.value.lastIndexOf("("));
You can use the selectionStart property on the input element. More information is on this MDN page. A working example is below.
function getCursorPosition(id) {
return document.getElementById(id).selectionStart;
}
function checkCursorPosition() {
alert(getCursorPosition('testInput'));
}
function backspace() {
var element = document.getElementById('testInput');
var cursorPosition = getCursorPosition('testInput');
element.value = element.value.substring(0, cursorPosition - 1) + element.value.substring(cursorPosition);
element.selectionStart = element.selectionEnd = cursorPosition - 1;
}
<input type="text" id="testInput" value="Example text" />
<button onclick="checkCursorPosition()">Check Cursor Position</button>
<button onclick="backspace()">Backspace</button>

Javascript variable scroll issue

I have a page whereby the user can press left + right buttons to scroll through numbers between 1-10.
The default value is 0 which displays blank.
There are two buttons at the bottom which allow the user to 'Clear' the number - reseting it to 0. Or to 'Shuffle', picking a random number.
After this the user can submit these numbers into a database.
My issue is, if the user were to scroll to 5 (for example), click shuffle then submit, it would submit '5' instead of the random number it should have generated.
Also if the user only clicks 'shuffle' then submit, it'll input '0'.
The issue with the 'clear' button is similar, if the user scrolls to 5, then hits reset, the variable would stay at '5' when submitted.
I'm probably overcomplicating something very simple, and im sorry if i am, but this is annoying me.
Thankyou ~
I'm not entirely certain what the problem is without looking at your code. I get the feeling it is something like this:
Javascript
var opNumb = 0; //default number
left = function(){if (opNumb>0) opNumb--;
updateNumb(opNumb);}
right = function(){if (opNumb<10) opNumb++;
updateNumb(opNumb);}
def = function(){opNumb=0;
updateNumb(opNumb);} //function to return to default
randomNumb = function(){opNumb = Math.floor(Math.random() * 11);
updateNumb(opNumb);}
updateNumb = function(Numb){document.forms[0].opVal.value = Numb;}
window.onkeydown = press; //bind keydown to press function
function press(e){
if (e.keyCode == 37) left();
if (e.keyCode == 39) right()
}
HTML form
<form id="frm1">
<input type="text" name="opVal" value="0"/><br />
<input type="button" value="left" onclick="left()"/><input type="button" value="right" onclick="right()"/><input type="button" value="Clear" onclick="def()"/><input type="button" value="Shuffle" onclick="randomNumb()"/><br />
<input type="button" value="Submit form" onclick="alert(opNumb);"/>
</form>​
What does your form look like? You're most likely having a problem setting a value?
Link to example
It sounds like your number isn't saving so whenever you update the number on the screen I would save the number then that way you should always be sending the number that you see.
var number = 0;
//All your events to call the different functions
function moveLeft{
//logic
reset(num);
}
function moveRight{
//logic
reset(num);
}
function shuffle{
//logic
reset(num);
}
function reset{
//logic
reset(num);
}
reset(num){
number = num;
//update the HTML
}

Change text box quantity, change picture upon hover with jQuery/Javascript

I would like to do 2 things in jQuery or Javascript,
Change with quantity in a text box with up and down arrows. The default qty is 1, and I want to increment by 1 when a user clicks the up arrow, and vice versa.
Can I change the arrow to another picture (color) when the mouse hovers on it?
Thank you.
I would recommend using click() command for changing the value in a textbox and the hover() command for changing the arrow to another picture (color)
for example, for the incrementer
$('#myImg')
.click( function() {
var num = $('#myTextbox').text();
if (!isNaN(num))
$('#myTextbox').text(parseInt(num,10) + 1);
.hover(
function() { $(this).css('background-image','over.jpg'), //over
function() { $(this).css('background-image','out.jpg') // out
)
1.)
<script>
function increase() {
var textbox = document.getElementById('textbox');
textbox.value = parseInt(textbox.value) + 1;
}
</script>
<input id="textbox" name="textbox" type="text" value="1">
up
2.) Should be down with CSS :hover

Categories