Last active
August 2, 2024 08:33
-
-
Save chamie/fc5725872182b50112a3 to your computer and use it in GitHub Desktop.
9 years later =)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Untitled</title> | |
<script> | |
const $ = (elementName) => document.querySelector(elementName); | |
const copyInput = (hiddenInput) => { | |
const mask = $("#mask").value; | |
const maskDigitsCount = mask.match(/_/g).length; | |
let output = mask; | |
const inputValue = hiddenInput.value + "|"; | |
inputValue | |
.substr(0, maskDigitsCount) | |
.split("") | |
.forEach(digit => { | |
output = output.replace("_", digit); | |
}); | |
$("#visibleInput").value = output; | |
} | |
const isKeyALlowed = (event) => | |
( | |
(((event.keyCode > 47) && (event.keyCode < 58) /* digits */ | |
|| (event.keyCode > 95) && (event.keyCode < 106)) /* NumPad digits */ | |
&& (event.currentTarget.value.length < 10)) | |
|| (event.keyCode == 8) //Backspace | |
); | |
let isCursorVisible = false; | |
const blink = () => { | |
if (document.activeElement == $("#hiddenInput")) { | |
if (isCursorVisible) { | |
$("#visibleInput").value = $("#visibleInput").value.replace("|", String.fromCharCode(160));// char, to look like a space but distinguishable at replace | |
} | |
else { | |
$("#visibleInput").value = $("#visibleInput").value.replace(String.fromCharCode(160), "|"); | |
} | |
isCursorVisible = !isCursorVisible; | |
} | |
} | |
setInterval(blink, 500); | |
</script> | |
</head> | |
<body> | |
Mask:<br> | |
<input id="mask" value="(___) ___-__-__" /><br> | |
Enter value: | |
<input type="number" onkeydown="return(isKeyALlowed(event))" style="opacity:0;" id="hiddenInput" | |
onkeyup="copyInput(this)"><br> | |
<input style="margin-top:-20px;font-family:monospace" id="visibleInput" onclick="$('#hiddenInput').focus()" | |
value="(|__) ___-__-__"> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An overcomplicated workaround to get an input field to work like a masked input while forcing mobile browsers to show a numeric onscreen keyboard.
Done by keeping the actual cursor in a hidden "number"-type input, copying the value on "keyup" and drawing a fake blinking cursor.