Search code examples
javascriptdrag-and-droppreventdefault

why if statement with e.preventDefault ? - drag and drop javascript


I'm following this example to make a javascript html5 DnD (drag and drop): http://www.html5rocks.com/en/tutorials/dnd/basics/

To prevent the default behavior for some browsers the default event is prevented. I understand the need. But why is there also an if statement?

function handleDragOver(e) { 
  if (e.preventDefault) {
    e.preventDefault(); // Necessary. Allows us to drop.
  }

// Why this if statement?, To me it seems double: if it is already there (if true), do it again...?

Thanks for anyone who has some time to explain this to a newbie in JavaScript.

Thanks!


Solution

  • The first call isn't actually calling the function, but simply checking to see if it is defined. The code is basically asking "is the e.preventDefault() method defined?" and then executing it if it is:

    // Is preventDefault() currently defined?
    if (e.preventDefault) {
         // Then do it.
         e.preventDefault(); 
    }
    

    Possible Reasoning

    The likely reason that this exists is that support for event.preventDefault() wasn't added in Internet Explorer until IE9, so code similar to the following may have been more common during those dark, pre-IE9 days :

    // An example of a pre-IE9 check for preventing default events
    (event.preventDefault) ? event.preventDefault() : event.returnValue = false;