E.preventDefault () doesn't work but event data is correct

I have event listeners applied to two elements that respond to the mousedown event. They work fine, but it brings up the right mouse button menu which I am trying to prevent.

I don't really understand why it doesn't work. 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 added comments to show which lines are working, which I tested with console.log. e

correctly set e.button

only responds to right click, so I don't know why e.preventDefault()

doesn't work in this case.

+3


source to share


1 answer


You need to add an event listener for the contextmenu like

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

      



JSFiddle

+4


source







All Articles