How to prevent images from being dragged from your website

Learn how to prevent images from being dragged from your website in this quick and easy guide.

Many web browsers allow visitors to drag images from your website to their devices by default if you are using the<img> tag to display each image.

The user-drag and user-select CSS properties can be used to prevent all such images on a website from being draggable:

img,
.no-drag {
	-webkit-user-drag: none;
	user-drag: none;
	-webkit-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	user-select: none;
}

Be sure to include the lines that involve vendor or browser prefixes such as ‑webkit, ‑moz and ‑ms as shown above.

The CSS code alone doesn’t cover all browsers, so the following JavaScript code is also needed:

function disableImgDragging() {
	var images = document.getElementsByTagName("img");
	for(var i = 0 ; i < images.length ; i++) {
		images[i].classList.add('no-drag');
		images[i].setAttribute('no-drag', 'on');
		images[i].setAttribute('draggable', 'false');
		images[i].addEventListener('dragstart', function( event ) {
			event.preventDefault();
		}, false);	
	}
}
disableImgDragging();

With both the above CSS and JavaScript code in place, all of the images on the website should no longer be draggable in as many browsers as possible.


Love our articles? HostM offers professional and helpful web hosting services with unlimited features and renewal rates that actually match our advertised rates.