How to prevent default actions in JavaScript?

What is a cross browser method? I need to prevent any default action for the image so that no drag and anything else will work by default.

+3
source share
3 answers

You can register the events that you want to cancel, and then either return falsefrom them or use them, Event.preventDefault()depending on the browser and the event.

+5
source
(function() {
    var onmousedown;
    if('onmousedown' in document && typeof document.onmousedown == 'function') {
        onmousedown = document.onmousedown;
    }
    document.onmousedown = function(e) {
        if(typeof e == 'undefined') {
            e = window.event;
        }
        if(!e.target) {
            e.target = e.srcElement || document;
        }
        if('nodeName' in e.target && e.target.nodeName.toLowerCase() == 'img') {
            if(e.preventDefault) {
                e.preventDefault();
            }

            // If you want to register mousedown events for
            // elements containing images, you will want to
            // remove the next four lines.
            if(e.stopPropagation) {
                e.stopPropagation();
            }
            e.cancelBubble = true;

            e.returnValue = false;
            return false;
        }

        if(onmousedown !== undefined) {
            onmousedown(e);
        }
    };
})();

You may need to do something similar to other events that you would like to prevent if this does not do what you want.

, , . , . JavaScript () , JavaScript.

+4

. " " .

dragging ( ), false mousedown.

+1

Source: https://habr.com/ru/post/1725371/


All Articles