Oskar Szura
Oskar Szura

Reputation: 2559

Why 'if' before preventDefault and stopPropagation

It's probably a rookie question but I can't either Google it or guess why it is this way.

el.addEventListener(
    'drop',
    function(e) {
        if(e.preventDefault) { e.preventDefault(); }
        if(e.stopPropagation) { e.stopPropagation(); }
        //... some other code

now... I used to just implement:

e.preventDefault();
e.stopPropagation();

without any 'if's, can someone give me a hint why I should place ifs before?

Upvotes: 0

Views: 98

Answers (1)

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

It makes sure preventDefault and stopPropagation indeed exist before executing them. Other ways of doing the same thing include:

var empty = function(){};
(e.preventDefault || empty)()
if(typeof e.preventDefault !== "undefined") e.preventDefault();

Upvotes: 3

Related Questions