Wednesday, 16 July 2014

Drag and Drop series- Setting up our JavaScript environment (Part 2/5)


Now, here's a good news. In the previous part in this series we completed all the CSS and HTML work that we needed for this series and this part on we'll focus only on the JavaScript. (There will probably be just another more part).

In this part we'll set up our environment by building a function that references all the HTML elements.


All of our initialization will take place inside a function called init(). We'll call this function when the web page loads so go ahead and set an event listener that calls this function when the window loads.
window.addEventListener("load", init)

Now let's start building our init function

We have 6 things to do in this function. Two things are to reference the image and the left box. The other two things are to set event listeners and override default functionality.

What is overriding default functionality? Well, many browsers treat the drag and drop API differently. So that our app looks similar in all platforms we have to disable the default functionality of the browser. To do this the event object gives us a function called preventDefault(). So let's see this in code:
function init(){
    // If you can't recall the ids
    // Check the previous post in this series

    img = document.getElementById("img");
    box = document.getElementById("left");

    // The event that is called when you start dragging
    img.addEventListener("dragstart", dragged);

    // The event that is called when you finish dragging
    box.addEventListener("drop", dropped);

    // The events that are called when you enter the box
    // and mouseover a box while dragging
    box.addEventListener("dragenter",function(e){e.preventDefault()});
    box.addEventListener("dragover",function(e){e.preventDefault()});
}

Conclusion

Well, that's pretty much it for this part of this series. We'll finish this program up in the next part and then we'll have an optional part for some cool additional functionality.

No comments:

Post a Comment