jQuery event.preventDefault() don't work unless debugging

900 Views Asked by At

I am trying to use this approach in order to convert GET parameters to POST. I also want the anchor to be properly handled even if the middle mouse button is clicked.

This is how I did the the event handlers binding:

$(document).ready(function () {
    $(".post").each(function(){
        $(this).mousedown(function(evt){
            switch(evt.which){
                case 1:
                case 2:
                    evt.stopPropagation();
                    evt.preventDefault();
                    get2post(evt);
                    break;
            }
        });
    });
});

When I click on the .post anchor, the browser sends the POST request, and then immediately aborts it, sending the supposedly prevented GET request instead.

Firebug reports that the POST request was aborted, and then the GET is sent

(Please do not mind the error that happens when the GET request is processed. This happens exactly because the parameters should be sent via POST, not GET)

Finally, when I debug the get2post functions, it works as expected. I don't have any clue about why the evt.preventDefault() line works only when debugging.

I tried it on Firefox and Chrome, and got the same outcome. What is happening here? Why the evt.preventDefault() don't work unless debugging?

1

There are 1 best solutions below

5
On BEST ANSWER

There is no default behaviour for anchor, button or input on mousedown event. You want to prevent default behaviour of click event instead.

$(function () {
    $('.post').on('click', function (evt) {
        switch (evt.which) {
            case 1:
            case 2:
                evt.stopPropagation();
                evt.preventDefault();
                get2post(evt);
                break;
        }
    });
});