Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework

Sponsors

About Me

Great Blogs

Using Native Drag and Drop in HTML 5 pages

This is going to be the eighth post in a series of posts regarding HTML 5. You can find the other posts here, here , here , here, here , here and here.

In this post I will show you how to implement Drag and Drop functionality in an HTML 5 page using JQuery.This is a great functionality and we do not need to resort anymore to plugins like Silverlight and Flash to achieve this great feature. This is also called a native approach on Drag and Drop.

I will use some events and I will write code to respond when these events are fired.

As I said earlier we need to write Javascript to implement the drag and drop functionality. I will use the very popular JQuery Library. Please download the library (minified version) from http://jquery.com/download

I will create a simple HTML page.There will be two thumbnails pics on it. There will also be the drag and drop area where the user will drag the thumb pics into it and they will resize to their actual size.

The HTML markup for the page follows

<!doctype html>
<html lang="en">
<head>
<title>Liverpool Legends Gallery</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" charset="utf-8" src="jquery-1.8.1.min.js"></script> 
<script language="JavaScript" src="drag.js"></script>  
</head>

<body>
<header>
<h1>A page dedicated to Liverpool Legends</h1>
<h2>Drag and Drop the thumb image in the designated area to see the full image</h2>
</header>


<div id="main">

<img src="thumbs/steven-gerrard.jpg"
 big="large-images/steven-gerrard-large.jpg" alt="John Barnes">


<img src="thumbs/robbie-fowler.jpg"
big="large-images/robbie-fowler-large.jpg" alt="Ian Rush">


<div id="drag">
<p>Drop your image here</p>
 </div>


</body>

</html>

 

There is nothing difficult or fancy in the HTML markup above. I have a link to the external JQuery library and another javascript file that I will implement the whole drag and drop functionality.

The code for the css file (style.css) follows



#main{
  float: left;
  width: 340px;
  margin-right: 30px;
}

#drag{
  float: left;
  width: 400px;
  height:300px;
  background-color: #c0c0c0;

}

These are simple CSS rules. This post cannot be a tutorial on CSS.For all these posts I assume that you have the basic HTML,CSS,Javascript skills.

Now I am going to create a javascript file (drag.js) to implement the drag and drop functionality.

I will provide the whole code for the drag.js file and then I will explain what I am doing in each step.

$(function() {
          var players = $('#main img');
          players.attr('draggable', 'true');
         
          players.bind('dragstart', function(event) {
              var data = event.originalEvent.dataTransfer;
              var src = $(this).attr("big");
              data.setData("Text", src);
              return true;
          });

          var target = $('#drag');

          target.bind('drop', function(event) {
            var data = event.originalEvent.dataTransfer;
            var src = ( data.getData('Text') );
           
            var img = $("<img></img>").attr("src", src);
            $(this).html(img);
            if (event.preventDefault) event.preventDefault();
            return(false);
          });

         
          target.bind('dragover', function(event) {   
            if (event.preventDefault) event.preventDefault();
            return false;
          });


           players.bind('dragend', function(event) {
             if (event.preventDefault) event.preventDefault();
             return false;
           });

        });

 

 In these lines

 var players = $('#main img');
 players.attr('draggable', 'true');

We grab all the images in the #main div and store them in a variable and then make them draggable.

Then in following lines I am using the dragstart event.

  players.bind('dragstart', function(event) {
              var data = event.originalEvent.dataTransfer;
              var src = $(this).attr("big");
              data.setData("Text", src);
              return true;
          });

 

In this event I am associating the custom data attribute value with the item I am dragging.

Then I create a variable to get hold of the dropping area

 var target = $('#drag');

Then in the following lines I implement the drop event and what happens when the user drops the image in the designated area on the page.

 target.bind('drop', function(event) {
            var data = event.originalEvent.dataTransfer;
            var src = ( data.getData('Text') );
            
            var img = $("<img></img>").attr("src", src);
            $(this).html(img);
            if (event.preventDefault) event.preventDefault();
            return(false);
          });

 The dragend  event is fired when the user has finished the drag operation

        players.bind('dragend', function(event) {
             if (event.preventDefault) event.preventDefault();
             return false;
           });

 When this method event.preventDefault() is called , the default action of the event will not be triggered.

Please have a look a the picture below to see how the page looks before the drag and drop takes place.

 

Then simply I drag and drop a picture in the dropping area.Have a look at the picture below

 

It works!!!

Hope it helps!!

 

Comments

Fabian said:

My spouse and I stumbled over here from a different web page and thought

I might as well check things out. I like what I see so now

i am following you. Look forward to checking out your

web page again.

# September 22, 2012 9:03 AM

Carper said:

Nice blog here! Also your web site loads up fast! What host are you using?

Can I get your affiliate link to your host?

I wish my web site loaded up as fast as yours lol

# September 22, 2012 4:40 PM

Bannister said:

Fantastic job. keep going!

# September 22, 2012 10:52 PM

Hobson said:

Fine way of explaining, and nice post to take data about my presentation subject

matter, which i am going to present in school.

# September 23, 2012 8:47 AM

Goins said:

This blog was... how do you say it? Relevant!! Finally I have found something that helped me.

Appreciate it!

# September 23, 2012 1:21 PM

Carder said:

I know this web page presents quality based posts and other stuff, is there any other website which gives these

stuff in quality?

# September 24, 2012 12:36 AM

Barksdale said:

Heya i am for the primary time here. I found this board and I

in finding It truly useful & it helped me out a lot.

I hope to offer one thing back and aid others such as you

aided me.

# September 24, 2012 9:47 AM

nikolaosk said:

@Carper . Τhe blog is hosted by Microsoft.The platform it runs on a blogging platform from Telligent

# September 25, 2012 7:41 PM

Ridgeway said:

I'm not sure where you're getting your info,

but good topic. I needs to spend some time learning much more or understanding

more. Thanks for wonderful info I was looking for this info for my mission.

# January 23, 2013 10:29 PM

Oshea said:

This piece of writing will help the internet people for setting up new webpage or even a weblog from start to end.

# February 20, 2013 6:12 AM

Bishop said:

I'll immediately snatch your rss as I can't in finding your email subscription hyperlink or newsletter service.

Do you've any? Kindly let me understand in order that I may just subscribe. Thanks.

# February 20, 2013 9:15 AM

Aguirre said:

Thanks for sharing your thoughts on ASP.NET. Regards

# February 26, 2013 6:21 PM

Collado said:

Hello There. I found your blog using msn. This is a very well written article.

I will make sure to bookmark it and return to read more of

your useful info. Thanks for the post. I will certainly return.

# February 27, 2013 8:48 PM

Blanton said:

I am truly happy to read this blog posts

which contains plenty of helpful information, thanks for providing such information.

# March 1, 2013 10:15 AM