Hello, guys in this tutorial we will disable the right click on the website using JavaScript.
JavaScript methods are used to disable the right click on the page. The used methods are listed below:
01. HTML DOM addEventListener() Method: This method attaches an event handler to the document.
Disable right click 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 to disable right click
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 https-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.
* { padding: 0; margin: 0; font-family: 'IBM Plex Sans', sans-serif; } body { display: flex; align-items: center; justify-content: center; height: 100vh; background: #f1f2f3; } button.btn { border: 0; padding: 12px 40px; font-size: 18px; background: #4b00ff; color: #fff; box-shadow: 5px 5px 25px 1px rgba(0,0,0,0.25); cursor: pointer; outline: 0; } .center { text-align: center; } small#disable_msg { display: block; margin: 20px 0; color: green; font-weight: 700; } h2 { margin: 20px 0; display: block; }