Hello guys in this tutorial we will disable the right click on website using JavaScript.
JavaScript methods are used to disable the right click on the page. The used methods are listed below:
-
HTML DOM addEventListener() Method: This method attaches an event handler to the document.
Example:
Attach a click event to a
<button>element. When the user clicks on the button, output Hello World in a<p>element with id='demo':
document.getElementById("myBtn").addEventListener("click", function() {
document.getElementById("demo").innerHTML = "Hello World";
});
In this tutorial we will use event.preventDefault() method.
First we need to create two files index.html and style.css then we need to do code for it.
Step:1
Add below code inside index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>How to disable right click using JavaScript</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="style.css" />
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans&display=swap" rel="stylesheet">
</head>
<body>
<div class="center">
<h2>Click on the button to disable right click</h2>
<button class="btn" onclick="contextmenu()">Click Me</button>
<small id="disable_msg"></small>
</div>
<script type="text/javascript">
var disable_msg = document.getElementById("disable_msg");
function contextmenu() {
document.addEventListener('contextmenu',
event => event.preventDefault()
);
disable_msg.innerHTML = "Right Click Disable";
}
</script>
</body>
</html>
Step:2
Then we need to add code for style.css which code i provide in below screen.
Download Css
Disable Right Click output:
For more interesting content like ▼▼▼
Top comments (0)