Languages
[Edit]
EN

JavaScript - after paste event Vanilla JS

2 points
Created by:
Kate_C
22250

In this article we would like to show how to handle onbeforepaste event in pure JavaScript.

By default paste event is executed before input element value property is set. It can cause problems during getting pasted text. Moreover beforepaste event is not available. There are some tricks how to do it.

Quick solution:

input.addEventListener('paste', function() {
    setTimeout(function() {
        console.log(input.value); // executed after paste event
    });
});

Check full examples below.

1. setTimeout after onpaste event example

This approach bases on the fact we are able to delay some logic and execute it immidiatelly after event occured.

1.1 Event property example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <input id="input" placeholder="Paste some text here..." />
  <script>

    var input = document.querySelector('#input');
    
    input.onpaste = function() {
    	setTimeout(function() {
        	console.log(input.value);
        });
    };
    
  </script>
</body>
</html>

1.2 Event listener example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <input id="input" placeholder="Paste some text here..." />
  <script>

    var input = document.querySelector('#input');
    
    input.addEventListener('paste', function() {
    	setTimeout(function() {
        	console.log(input.value);
        });
    });
    
  </script>
</body>
</html>

2. keyup event with onpaste example

This approach uses flag to check what event occured before input event.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <input id="input" placeholder="Paste some text here..." />
  <script>

    var pasted = false;
    var input = document.querySelector('#input');
    
    input.addEventListener('paste', function() {
    	pasted = true;
    });
    
    input.addEventListener('input', function() {
    	if (pasted) {
          	pasted = false;
        	console.log(input.value); // executed after paste event
        }
    });
    
  </script>
</body>
</html>

 

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join