Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.ondragstart not equivalent to .addEventListener("dragstart"

I want to make an img element unselectable and undraggable because I'm using it as a window resizing control (clicking and dragging on the surrounding div resizes a window).

It works perfectly fine as the following:

noSelect[x].ondragstart = function() {return false};

But since this will be used in a firefox(3.6.*) extension which uses an XPCNativeWrapper around every HTMLElement, I cannot use ".onsdragstart" and have to use ".addEventListener"

The problem is the equivalent to the above code isn't working. Clicking and dragging the img triggers firefox's default image dragging, instead of resizing my window in the following:

noSelect[x].addEventListener("dragstart", function () {return false}, false)

Are the two lines of code quoted above not equivalent?

Full context for unselectable objects:

var noSelect = document.getElementsByClassName("noSelect")
    for (x in noSelect) {
        if (x == "length")
            break
        noSelect[x].unselectable = "on";
        noSelect[x].onselectstart = function(){return false};
        noSelect[x].ondragstart = function() {return false};
        noSelect[x].style.userSelect = "none"; // w3c standard
        noSelect[x].style.MozUserSelect = "none"; // Firefox
    }
like image 635
TinyTimZamboni Avatar asked Jan 14 '11 06:01

TinyTimZamboni


2 Answers

addEventListener registers an EventListener, which doesn't have any special return code treatment.

Returning false from most on* event handlers cancels the event per the HTML spec, in regular EventListener this is achieved by calling event.preventDefault() as Neil mentioned in his answer.

like image 116
Nickolay Avatar answered Sep 30 '22 15:09

Nickolay


I don't know why function() { return false; } doesn't work, but I do know that function(event) { event.preventDefault(); } will work in Firefox.

like image 35
Neil Avatar answered Sep 30 '22 13:09

Neil