HTML5 INPUT type='number' - distinguish between focus and value-change mouse clicks

可紊 提交于 2019-12-05 05:36:18

Here's it! When the user change the value by clicking on up/down arrows it triggers oninput, and conveniently it's triggered between onmousedown and onmouseup

<script>
    window.onload = function() {
        changeType = 'none';
        var input = document.getElementById('number');
        var events = [
                "mousedown",
                "mouseup",
                "input",
                "keypress"
            ];
        events.map(function(ev){
            input.addEventListener(ev,function(){
                switch(ev) {
                case 'input':
                    if(changeType!='keypress') changeType = 'input';
                break;
                case 'mouseup':
                    switch(changeType) {
                        case 'mousedown':
                            console.log('normal click');
                        break;
                        case 'keypress':
                            console.log('click with edit via keyboard');
                        break;
                        case 'input':
                            console.log('click on up/down arrows');
                        break;
                    }
                break;
                default:
                    changeType = ev;
                break;
            }
            },false);
        });
    }
</script>
<input type="number" id="number">

EDIT Now it handles also keyboard edit when mouse is pressed.


EDIT Is much better now, thanks to gion_13

Here is a demo of how you can capture and analyze which events change the input and in what order.

html:

<input type="number" id="number" />

script:

var input = document.getElementById('number'),
    events = [
        "click",
        "mousedown",
        "mouseup",
        "focus",
        "change",
        "input",
        "keydown",
        "keypress",
        "keyup"
    ];
events.forEach(function(ev) {
    input.addEventListener(ev, function() {
        console.log(ev, ' => ', input.value);
    }, false);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!