Sir
Sir

Reputation: 8280

e.preventDefault() not working, but event data is correct

I have event listeners applied to two elements which react to a mousedown event. They work fine, but it causes the right click menu to appear which i am trying to prevent.

I am not fully understanding why it is not working. This is my code:

function moveDiv(e){    
    e.preventDefault();    //not working

    if(e.button == 2){     //works on right click only, so e is correct data
        console.log(this); //works - shows element data
    }
}

function load(){    

    function addEvents(){           
        var d = getDiv('overview'); //getDiv gets the element by id
            d.addEventListener('mousedown',moveDiv,false);
        var d = getDiv('login_data');
            d.addEventListener('mousedown',moveDiv,false);
    }

    templateLoad('main.html',addEvents); //works: async loads page, then call function 'addEvents'  
}

load();

I have added comments to show which lines are working, which i tested using console.log. e is correct given e.button responds only on right click, so i don't know why e.preventDefault() fails to work in this case.

Upvotes: 3

Views: 102

Answers (1)

Phil
Phil

Reputation: 164723

You need to add an event listener for the contextmenu event, eg

.addEventListener('contextmenu', function(e) {
    e.preventDefault();
}, false);

JSFiddle

Upvotes: 4

Related Questions