Keyboard Playground

by tabalinas

HTML

<input type="text">
<button>Select</button>

JavaScript

$("input").on({
    "keydown": function(e) {
        console.log("keyDown", e);
    },
    "keypress": function(e) {
        console.log("keyPress", e);
    },
    "keyup": function(e) {
        console.log("keyUp", e);
    },
    "input": function(e) {
        e.preventDefault();
        console.log("input", e);
    }
});

var $input = $("input");

window.setSelection = function ($input, start, end) {
    var length = $input.val().length;
    end = (end < 0 || end > length) ? length : end;
    start = (start < 0 || start > end) ? 0 : start;
    
    $input.get(0).setSelectionRange(start, end);
    $input.focus();
}

$("button").on("click", function(e) {
    setSelection($input, 0, 5);
});