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.
-
All is clear. Read carefully.Ale Anderson– Ale Anderson2009-12-11 07:19:13 +00:00Commented Dec 11, 2009 at 7:19
-
4Ale Anderson, if people ask you to clarify your question you might consider that what seems clear to you isn't necessarily clear to others. Your question is extremely unclear.eyelidlessness– eyelidlessness2009-12-11 08:10:56 +00:00Commented Dec 11, 2009 at 8:10
-
2At least define what the "default action on an image" is. This is new to me.Crescent Fresh– Crescent Fresh2009-12-11 11:32:37 +00:00Commented Dec 11, 2009 at 11:32
-
1stackoverflow.com/questions/1357118/…OrangeDog– OrangeDog2013-01-07 15:19:57 +00:00Commented Jan 7, 2013 at 15:19
3 Answers
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.
1 Comment
(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.
Comments
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.
6 Comments
document.onmousedown = function(e) { if(typeof e == 'undefined') e = window.event; if(e.preventDefault) e.preventDefault(); if(e.stopPropagation) e.stopPropagation(); e.returnValue = false; return false; }; But obviously this will have tons of nasty side-effects.