What is the cross-browser method? I need to prevent any default action on an image, so that neither dragging nor anything else will fire on a default bases.
You can only cancel specific events. You cannot "globally cancel" default actions.
To specifically cancel dragging
an image (which is only a default function in some browsers), return false
to the mousedown
event.
(function() {
var onmousedown;
if('onmousedown' in document && typeof document.onmousedown == 'function') {
onmousedown = document.onmousedown;
}
document.onmousedown = function(e) {
if(typeof e == 'undefined') {
e = window.event;
}
if(!e.target) {
e.target = e.srcElement || document;
}
if('nodeName' in e.target && e.target.nodeName.toLowerCase() == 'img') {
if(e.preventDefault) {
e.preventDefault();
}
// If you want to register mousedown events for
// elements containing images, you will want to
// remove the next four lines.
if(e.stopPropagation) {
e.stopPropagation();
}
e.cancelBubble = true;
e.returnValue = false;
return false;
}
if(onmousedown !== undefined) {
onmousedown(e);
}
};
})();
You may need to do something similar to other events you'd like to prevent, if this doesn't do what you want.
Also it's worth noting that if you're trying to prevent people from downloading images from a page to their computer, you will not succeed. If a browser can download an image, so can the user. Using JavaScript to block (some) attempts is easily circumvented by simply disabling JavaScript.
You can register the events you want to cancel, and then either return false
from them or use Event.preventDefault()
, depending on the browser and event.