Skip to content

Instantly share code, notes, and snippets.

@uddhabh
Created February 19, 2023 05:25
Show Gist options
  • Save uddhabh/03c82c8cf5c93ce9551a3658b0026a44 to your computer and use it in GitHub Desktop.
Save uddhabh/03c82c8cf5c93ce9551a3658b0026a44 to your computer and use it in GitHub Desktop.
Disable right-click and dragging on images
function disableRightClickAndDragOnImages() {
// Get all images on the page
const images = document.getElementsByTagName('img');
// Loop through the images and disable right-click and dragging on each one
for (let i = 0; i < images.length; i++) {
images[i].addEventListener('contextmenu', event => {
event.preventDefault();
});
images[i].addEventListener('mousedown', event => {
if (event.button === 2) {
event.preventDefault();
}
});
images[i].addEventListener('keydown', event => {
if (event.key === 'ContextMenu') {
event.preventDefault();
}
});
images[i].addEventListener('dragstart', event => {
event.preventDefault();
});
}
}
disableRightClickAndDragOnImages();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment