Sometimes, we want to detect paste in input box with JavaScript.
In this article, we’ll look at how to detect paste in input box with JavaScript.
How to detect paste in input box with JavaScript?
To detect paste in input box with JavaScript, we can listen to the paste event of the input.
For instance, we write:
<input type="text" />
to add an input.
Then we write:
const input = document.querySelector('input')
input.onpaste = (e) => {
setTimeout(() => {
console.log(e.target.value)
}, 0)
}
to select the input with document.querySelector
.
Then we set the input.onpaste
property to a function that gets the pasted value from e.target.value
.
We put the log inside the setTimeout
callback since the input is only updated one tick after pasting the content.
Conclusion
To detect paste in input box with JavaScript, we can listen to the paste event of the input.