Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Which event occurs in JavaScript when an element's content is cut?
The oncut event occurs when an element's content is cut using Ctrl+X or the right-click context menu. This event is commonly used with input fields, textareas, and other editable elements to track when users cut text.
Syntax
element.oncut = function() {
// Code to execute when content is cut
};
// Or using addEventListener
element.addEventListener('cut', function(event) {
// Code to execute when content is cut
});
Example: Basic oncut Event
<!DOCTYPE html>
<html>
<head>
<title>Cut Event Example</title>
</head>
<body>
<input type="text" id="textInput" value="Select and cut this text" style="width: 300px; padding: 5px;">
<p id="output">Cut some text to see the event trigger</p>
<script>
document.getElementById('textInput').oncut = function() {
document.getElementById('output').innerHTML = "Text was cut from input field!";
};
</script>
</body>
</html>
Example: Using addEventListener with Event Object
<!DOCTYPE html>
<html>
<head>
<title>Cut Event with Details</title>
</head>
<body>
<textarea id="textArea" rows="4" cols="40">This is sample text. Select and cut any part of it.</textarea>
<div id="status"></div>
<script>
document.getElementById('textArea').addEventListener('cut', function(event) {
let cutText = window.getSelection().toString();
document.getElementById('status').innerHTML =
"<p>Cut event triggered!</p>" +
"<p>Cut text: '" + cutText + "'</p>" +
"<p>Target element: " + event.target.tagName + "</p>";
});
</script>
</body>
</html>
Event Properties
The cut event provides access to several useful properties:
- event.target - The element where the cut occurred
- event.clipboardData - Contains the data being cut (in some browsers)
- window.getSelection() - Gets the selected text being cut
Common Use Cases
- Logging user interactions for analytics
- Validating or processing cut content
- Providing user feedback when content is cut
- Implementing custom clipboard functionality
Browser Compatibility
The oncut event is supported in all modern browsers including Chrome, Firefox, Safari, and Edge. It works with form elements like input fields, textareas, and contenteditable elements.
Conclusion
The oncut event provides a reliable way to detect when users cut content from your web page elements. Use it to enhance user experience by providing feedback or implementing custom clipboard behavior.
Advertisements
