Prevent image selection and dragging behavior

When writing JavaScript that allows images to be dragged and dropped on a web page, the browser's default drag and selection behavior can get in the way. Here are cross-browser ways to disable these default behaviors...

Prevent selection:
HTML
<img style="moz-user-select: none" unselectable="on" onseletstart="return false;" />

or JavaSript
function preventSelection(element) {
element.style.MozUserSelect = 'none';
element.unselectable = 'on';
element.onselectstart = function() { return false; };
}

Prevent drag for images and links:
HTML
<img onmousedown="return false;" ondragstart="return false;" />

or JavaScript
function preventDrag(element) {
element.onmousedown = function() { return false; };
element.ondragstart = function() { return false; }; //I.E.
}

1 comment: