JavaScript

JavaScript in Action: How to Disable Image Drag & Right-Click – A Practical Guide Using oncontextmenu, onselectstart, and onmousedown

Protecting website content is an ongoing challenge for creators and web developers. Especially when it comes to preventing unauthorized use of images and text, technical measures are required. In this article, we’ll show you how to disable right-clicking and image dragging (saving) on a page using JavaScript’s oncontextmenu, onselectstart, and onmousedown.

Basic Settings with CSS

Let’s start by setting the basic styles of the page with CSS. At this stage, the focus is on organizing visual elements. The following code sets the base font size and header style of the site.

<style type="text/css">
body{
  text-align: center;
  font-size: 16px;
}
h1{
  text-align: center;
  font-size: 32px;
  line-height: 1.6em;
  padding: 30px 0;
}
</style>

Protecting Images Using HTML

Next, we’ll use HTML to disable image dragging. Here, we use a dummy image named dummy1.jpg and inform users that dragging is disabled for this image.

<h1>Right-clicking and image dragging are disabled on this page.<br>Try right-clicking or dragging the image below.</h1>

<div><img src="dummy1.jpg" alt="Right-click and drag disabled"></div>

Implementing Restrictions with JavaScript

Here’s the core part. We use JavaScript to disable right-clicking and image dragging (saving) on the page. You can block these actions by using the oncontextmenu, onselectstart, and onmousedown events.

<script type="text/javascript">
// Disable right-click
document.oncontextmenu = function(){ return false; };
document.body.oncontextmenu = "return false;"

// Disable dragging
document.onselectstart = function(){ return false; };
document.onmousedown = function(){ return false; };
document.body.onselectstart = "return false;"
document.body.onmousedown = "return false;"
</script>

Demo Page: Disabling Right-Click and Image Dragging with oncontextmenu, onselectstart, and onmousedown

You can see how this code works in action through the demo page below. This demo uses the code above, giving you a clear idea of how it can be applied to a real website.

Demo page using oncontextmenu, onselectstart, and onmousedown to disable right-click and image dragging

Conclusion

Website protection is essential for safeguarding copyrights. The JavaScript method introduced here offers a simple yet effective way to protect your pages. However, keep in mind that no protection is perfect, and it’s important to continuously explore new methods.

Update: 2024/09/12

For a more effective way to disable image dragging and right-clicking, please refer to the following article. It provides improved methods and descriptions.

Protect Your Web Images! How to Fully Block Right-Click & Drag Saving with JavaScript and CSS

 
*Please use this method at your own discretion.
Do not copy the Google Analytics tag in the demo page’s head section.