Handling Clipboard Paste Event in Browser
If not regularly writing JavaScript code for browsers, one can quickly get out of touch with all the APIs that are already supported in modern browsers. When I recently had to customize the way data is pasted into an input field on a web page, I started out with the assumption that I'll have to detect changes in the input field after they are already pasted. As I was doing some research on the best way to do that, I learned that I can just use the clipboard events instead.
When the page is loaded, I can simply add an event listener for the paste event on my input field, get the data from the clipboard in the required format (text in my case) and process it as necessary:
document.addEventListener('DOMContentLoaded', function() {
const input = document.getElementById('number-only');
input.addEventListener('paste', function(event) {
event.preventDefault();
event.stopPropagation();
const pastedText = event.clipboardData.getData('text');
const numbersOnly = pastedText.replace(/\D/g, '');
input.value = numbersOnly;
});
});
The code above expects an input field with its id
value set to number-only
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<form>
<input name="number-only" id="number-only">
</form>
<script src="form.js"></script>
</body>
</html>
As one can imply from the id, I strip the clipboard content of non-numeric characters and overwrite any existing input in the field with what remains. I didn't expect it to be this easy.