Teoman Tıngır
Teoman Tıngır

Reputation: 2866

input event - losing focus while dragging input element

I'm trying to make a score module using a range input. I'm using the input event to achieve this. The range input works fine, but when I add event, it loses focus shortly after dragging begins.

This is how it looks:

Screenshot

document.querySelector("#score").addEventListener("input", e => {
  console.log(e.target.value);
});
<input type="range" min="1" max="10" value="10" draggable="true" class="score theme" id="score" step="0.1">

Upvotes: 2

Views: 1358

Answers (3)

Aryan Mediratta
Aryan Mediratta

Reputation: 93

This seems to be a problem with the draggable="true" attribute and not the JavaScript code. The draggable attribute allows us to make the element draggable around the DOM, i.e. from one position to another in the viewport.

Therefore, when one tries to drag the range handle, the whole slider gets dragged along, instead of just the handle, which is what you described as "losing focus".

So, the solution is to simply remove the draggable=true attribute. I made a pen on CodePen to demonstrate this. https://codepen.io/aryan_02/pen/WPNBYm

Notice what the draggable attribute does. I hope this helps you.

Upvotes: 1

Christian Vincenzo Traina
Christian Vincenzo Traina

Reputation: 10384

That happens because you added draggable="true" to the element. So the behaviour is ambiguous, should the browser allow you to move the trackball or should the browser drag the element around the page?

The two behaviours are conflicting, so in the first moment it works properly as an input range and you're able to move it around, but then it allows you to drag the element.

What's your expected behaviour?

document.querySelector("#score").addEventListener("input", e => {
    console.log(e.target.value);
 });
    <input type="range" min="1" max="10" value="10" class="score theme" id="score" step="0.1">

    

Upvotes: 2

MTCoster
MTCoster

Reputation: 6145

draggable="true" doesn’t do what you think it does. An <input type="range"> has a draggable component to it by default. The draggable attribute makes it so that you can drag the entire element.

Removing this attribute gives the expected behaviour:

document.getElementById('score').addEventListener('input', e => {
  console.log(e.target.value);
});
<input type="range" min="1" max="10" value="10" id="score" step="0.1">

Upvotes: 2

Related Questions