Preview:
-
Disabling Right Click Using JavaScript
- HTML Code
- Javascript Code
Disabling Right Click Using JavaScript
Hello Developers and Welcome to My Blogspot! In this post, we'll explore how to disable the right-click functionality using JavaScript in an HTML document. Disabling right-click can be useful in certain scenarios, such as protecting images or content on your website. Now, let's dive into the code:
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Try RIght Click</title>
</head>
<style>
h1 {
display: flex;
justify-content: center;
}
</style>
<body>
<h1>Right Click Disable in JS</h1>
<script>
document.addEventListener("contextmenu", (event) => {
alert("Right-click disabled!");
event.preventDefault();
});
</script>
</body>
</html>
Output
Try Right Click
Explanation:
This script disables right-click functionality on the webpage.
1.Event Listener for contextmenu:
document.addEventListener("contextmenu", (event) => {
e.preventDefault();
});
- "document.addEventListener": This method is used to attach an event handler to the document.
- "contextmenu": This specifies the event type that we are listening for. The contextmenu event is fired when the user attempts to open the context menu, which typically happens when the user right-clicks on the page.
2.Arrow Function:
().=>
- This is an arrow function, which is a concise way to write anonymous functions in JavaScript. It will be executed whenever the contextmenu event is triggered.
3.Alert Box:
alert("right click disabled");
- This line shows an alert box with the message "right click disabled" when the contextmenu event occurs. An alert box is a popup dialog that displays a message to the user and waits for the user to dismiss it by clicking "OK".
4.Prevent Default Action:
event.preventDefault();
- event.preventDefault(): This method prevents the default action associated with the event. In this case, it stops the context menu from appearing when the user right-clicks on the page.
4.Prevent Default Action:
event.preventDefault();
- event.preventDefault(): This method prevents the default action associated with the event. In this case, it stops the context menu from appearing when the user right-clicks on the page.
Process of Execution
- Adding the Event Listener
- Showing an Alert
- Preventing the Default Behavior
The script adds an event listener to the entire document for the
Inside the function, the
The