---
description: <input> element as "slider".
---

# type="range"

🔰 [HTML](../..) ⟩ [Elements](..) ⟩ [\<input>]() ⟩

{% hint style="info" %}
**input** vs. **change** event

[oninput](https://www.w3schools.com/jsref/event_oninput.asp) is similar to the [onchange](https://www.w3schools.com/jsref/event_onchange.asp) event. The difference is that the [oninput](https://www.w3schools.com/jsref/event_oninput.asp) event occurs **immediately** after the value of an element has changed, while [onchange](https://www.w3schools.com/jsref/event_onchange.asp) occurs when the element loses focus, **after** the content has been changed.

簡單說，當我們**拖曳滑桿**的時候，**隨時**都會觸發 [oninput](https://www.w3schools.com/jsref/event_oninput.asp) 事件，但 [onchange](https://www.w3schools.com/jsref/event_onchange.asp) 事件是拖曳完**放開滑鼠後**才會**觸發一次**。
{% endhint %}

{% tabs %}
{% tab title="JS" %}
```javascript
const {log} = console;

const control = $('#control');
const div3 = $('#div3');
const label = $('#label');
const calc = $('#calc');

// marginControl.oninput
control.addEventListener('input', (e) => {
    let x = e.target.value;
    let percent = x + '%';
    label.textContent = 'marginTop: ' + percent;
    calc.textContent = `${percent} x 200px = ${2*x}px`
    div3.style.marginTop = percent;
});

// ⭐️ 自動跑一次 'oninput' event
control.dispatchEvent(new Event('input'));


// $ ⭐️ selector
function $(selector, parent = document){
  return parent.querySelector(selector);
}
```
{% endtab %}

{% tab title="CSS" %}
```css
#div1 {
    width: 200px;
    border: 1px solid black;
}

#div2, #div3 {
    height: 100px;
}

#div2 {

    /* ⭐️ vertical & horizontal align */
    display: flex;
    justify-content: center;
    align-items: center;

    background-color: rgba(255, 0, 0, 0.3);
    font-weight: bold;
}

#div3 {
    margin-block-start: 10%;
    background-color: rgba(0, 255, 21, 0.3);
}
```
{% endtab %}

{% tab title="HTML" %}
```markup
<input type="range" id="control" min="-100" max="100" value="0">
<label for="marginControl" id="label"></label>

<p>
  margin 若設定 %，則以「父元素寬度」為準。<br />
  <span id="calc"></span>
</p>

<div id="div1">
  <div id="div2">
    <p>200 x 100</p>
  </div>
  <div id="div3"></div>
</div>
```
{% endtab %}
{% endtabs %}

{% embed url="https://codepen.io/lochiwei/pen/mdmLvVZ" %}

