I would like to be able to focus on an input element of the type 'range', in other words, the default slider, so that the slider could be dragged without the user actually clicking on it.
The obvious solution would be to just use sliderelement.focus()
.
This however doesn't work.
I found here that the reason for this, is that I have to call this method on the handle of the slider.
The class of the slider handle should be 'ui-slider-handle'.
But for some reason document.querySelector('.ui-slider-handle')
returns null
.
The weird part is that this does work with JQuery when I use $('.ui-slider-handle')
.
I made this fiddle to clarify my problem. I would like to solve this using only Javascript.
--- edit ---
Perhaps I wasn't clear enough in my explanation. The class ui-slider-handle
is not a custom class I added to the slider handle, since I cannot access the handle. I expected this to be the default class based on the answer I found (which I stated earlier).
In your fiddle, the querySelector is correct.
Your jQuery will always return true like that though.
For example change var handle2 = document.querySelector('.ui-slider-handle');
to a made up class like var handle2 = document.querySelector('.ui-slider-handlesdfsdfsdfsdf');
and it returns true.
If you want to check if an element exists you can use .length.
So just add .length to your selector and they will both return false.
var handle1 = $('.ui-slider-handle').length;
var handle2 = document.querySelector('.ui-slider-handle');
$('#1').html('JQuery, handle found: ' + (handle1 ? 'true' : 'false'))
$('#2').html('Javascript, handle found: ' + (handle2 ? 'true' : 'false'))
To put focus on the range element simply use .focus()
.
Here is an example. Use the buttons and your arrow keys to see that it is gaining/losing focus on the element.
function getFocus() {
document.getElementById("myRange").focus();
}
function loseFocus() {
document.getElementById("myRange").blur();
}
<input type="range" id="myRange" value="50">
<p>Click the buttons below to give focus and/or remove focus from the slider control.</p>
<button type="button" onclick="getFocus()">Get focus</button>
<button type="button" onclick="loseFocus()">Lose focus</button>