Disable image dragging in FireFox

FireFox 3 has a behaviour where clicking on image (even background image) and moving your mouse will start to drag that image around. Actually, when you drag an image, the browser thinks you want to save it to the desktop, so it starts default dragging action. To disable image dragging in FireFox, you will have to prevent default action on mousedown event for the image. Please try to drag left and right image.

Default behaviour
drag me
Dragging disabled
drag me if you can

<!-- left image (default behaviour) -->
<img src="spider1.png">

<!-- right image (dragging disabled) -->
<img src="spider2.png" onmousedown="if (event.preventDefault) event.preventDefault()">

If you write event.preventDefault() only (without testing), then IE will throw an error. Disabling, or event cancelation is accomplished by calling the Event’s preventDefault method. preventDefault cancels the event if it is cancel-able, without stopping further propagation of the event. If you want to disable dragging for all images on the page, then you can use the following JavaScript code:

// register onLoad event with anonymous function
window.onload = function (e) {
    var evt = e || window.event,// define event (cross browser)
        imgs,                   // images collection
        i;                      // used in local loop
    // if preventDefault exists, then define onmousedown event handlers
    if (evt.preventDefault) {
        // collect all images on the page
        imgs = document.getElementsByTagName('img');
        // loop through fetched images
        for (i = 0; i < imgs.length; i++) {
            // and define onmousedown event handler
            imgs[i].onmousedown = disableDragging;
        }
    }
};

// disable image dragging
function disableDragging(e) {
    e.preventDefault();
}

Small but useful tips that can save time.
;)

26 thoughts on “Disable image dragging in FireFox”

  1. thanks a lot, I’d been looking for a script that could do this for a while… working great in Opera 12 (last Presto release). cheers

  2. hey thanks for your post , you save me from more search in google for the find this . thanks again mate

Leave a Comment