Try Tuts+ Premium, Get Cash Back!
Click and Drag With Javascript

Quick Tip: Create A “Click And Drag” Function With JavaScript

Tutorial Details
  • Difficulty: Beginner
  • Completion Time: 15 Minutes

In many modern web applications, developers look for ways to make it easier and more intuitive for users to interact. A drag and select function can help your users select multiple objects quickly.

Step 1

We first need to create the group of objects that will be selected. More likely than not, most people will use server side script such as C# or PHP. Since that is beyond the scope of this tutorial, I will instead create them by hand. We can use most tags as objects. The only requirement is that the object must have basic mouse events assigned to them. For this tutorial I will simply use a table with two rows and five cells filled with DIVs with some basic CSS to give them shape.

The most important part in creating the objects is the ID’s; they all need to have one similar name. Mine will be ‘box’ – and then a unique number after the name. Consequently, our first element’s ID will be ‘box1′ and our last will be ‘box10′. Now we just need to add the mouse events. For each DIV we need to assign its “onmousedown” to our javascript function and pass in the object that is calling the function with the ‘this’ keyword

<table>
	<tr>
		<td><div id="1d" onmousedown="StartDragSelect(this);"></div></td>
		<td><div id="2d" onmousedown="StartDragSelect(this);"></div></td>
		<td><div id="3d" onmousedown="StartDragSelect(this);"></div></td>
		<td><div id="4d" onmousedown="StartDragSelect(this);"></div></td>
		<td><div id="5d" onmousedown="StartDragSelect(this);"></div></td>
	</tr>
	<tr>
		<td><div id="6d" onmousedown="StartDragSelect(this);"></div></td>
		<td><div id="7d" onmousedown="StartDragSelect(this);"></div></td>
		<td><div id="8d" onmousedown="StartDragSelect(this);"></div></td>
		<td><div id="9d" onmousedown="StartDragSelect(this);"></div></td>
		<td><div id="10d" onmousedown="StartDragSelect(this);"></div></td>
	</tr>

</table>

Step 2

Now that we have our basic HTML done, we need to write the javascript. There are three primary parts to our javascript function: The action that happens every time you select or deselect an object, the action that starts the drag after the first click, and the action that stops the drag select. Before any of that we need to make a javascript function and pass in one variable called ‘obj’ this will be the object that is called this event.

function StartDragSelect(obj)
{

}

For the action that triggers after an object is selected or deselected, we first need a way for our function to know if this object is currently selected or deselected. You can use most attributes to do this, but I find the best way is with a CSS class. Not only will the CSS class tell javascript if the object is selected or not but you can also add CSS rules to the selected class so that users will be able to visually distinguish which objects are selected. For the javascript, all we need is a simple if -else statement. For this demo I’m going to update a span with the total number of selected objects, but you could also call ajax functions and other fun things here to make the drag select more powerful.

function StartDragSelect(obj)
{
	if (obj.className == "selected")
	{
		obj.className = "";
		selectNum--;
	}
	else
	{
		obj.className = "selected";
		selectNum++;
	}
	document.getElementById("selectCount").innerHTML = selectNum;
}

To start the drag select, we will use a “for loop” to take each object’s onmousedown event and assign it to the object’s onmouseover event. If we were using a server side script to generate our objects we would want to also pass in the total number of objects to the javascript function so the loop will work, but since we created them by hand we can hard code the number.

for(i=0;i<11;i++)
{
document.getElementById(i+'d').onmouseover = document.getElementById(i+'d').onmousedown
}

The stop action will be assigned to the onmouseup event of the object that started the drag select. To do this we will use an anonymous function to tell javascript what to do when the onmouseup event triggers. Then we will use a "for loop" to reassign the onmouseup event and make the onmouseover event null.

obj.onmouseup = function() 
{
	for(i=1;i<11;i++)
	{
		document.getElementById(i+'d').onmousedown = document.getElementById(i+'d').onmouseover;
		document.getElementById(i+'d').onmouseover = null;
	}
}

You're done! Obviously, this example is trivial and uses embedded Javascript (for the sake of simplicity). But, I'm sure you can imagine the possibilities! Have a better way?

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://theplayoffpush.com Mike

    Nice tut. Really like the feature.

  • http://talkingtofu2.iblogger.com Taylor Satula

    Cool demo. Ididn’t think this one would be good but it was after all

  • http://ha.xors.org Braden Keith

    Nice, I was thinking it was going to pick it up and drag, I would like to see that btw, but this is good practice

  • Simon

    Like Braden I also thought I was going to see a drag and drop, but this was something completely different, loved it :) Totally different use for click and drag.

  • http://www.richanomix.com Richard Neary

    Awesome tutorial, wasn’t what I was expecting but great nevertheless. And tables?! that’s so 90′s…

  • http://cyberantix.org Connor

    Wow…not even attached to a framework too! haha. But tables…come on…

    Nice quick tip nonetheless

  • http://newsreviewshowtos.blogspot.com Will

    I think I broke it… If you click and drag enough you won’t be able to anymore… bug? Thoughts?

  • http://www.christianbiggins.com Christian

    Nice one, this will come in handy.

  • http://www.insicdesigns.info insic

    why use tables?

  • http://www.jamielottering.com jamie lottering

    Not sure why everyone is hating on the use of tables for this -quick- tip…they served their purpose for this particular tutorial. Don’t hate tables just for the sake of hating tables, it’s a bit irrelevant here

  • http://www.gsm-nis.edu.yu SecretFile

    Nice but why u use table and inside u have divs…that doesn’t make sense???

  • grazz

    There, more basic tips like this one would be useful for beginners like me. Thanks!

  • http://enhance.qd-creative.co.uk James

    Yuck! Tables and inline JavaScript!??
    Anyway, nice quick tip! 8)

  • http://www.freshclickmedia.com Shane

    @James – couldn’t agree more with your first comment line.

    I’d have thought that an unordered list would have been more semantically correct, but hey – thanks for the tip.

  • http://www.jaysalvat.com/ Jay Salvat

    Hi,
    Glad to see some regular javascript, framework free even if in-line javascript are now evil.

    I agree that unordered list would have been a better choise than the actual table, but I presume those layout and semantic things are not the purpose of this evening tip.

    However, watch out, ID can’t start by a number to validate.
    ID=”1d” > wrong
    ID=”d1″ > right

  • http://laminbarrow.com Lamin Barrow

    Cool.. the first thing thing to my mind was a fancier replacement for checkboxes.

  • http://www.satedproductions.com Michael Thompson

    Hating tables for the sake of tables is absurd. Inline JavaScript…okay, that’s a bit nasty. But don’t hate tables just because you read that they’re evil on a standards blog a while back — they’re perfect for tabular data (tabular, tables…get it?) and for quick examples on NETTUTS.

  • http://www.bugeyes.de Marvin

    very usable! well explained!

  • http://www.1pixelbrush.com Dan

    Great tip! Tables are awesome, I eat off them.

  • http://enhance.qd-creative.co.uk James

    @Michael – It would’ve required minimal effort to semantically markup this demonstration. Why use tables when there is a cleaner and just-as-easy-to-code alternative?

  • http://www.benmillsdesigns.com Ben Mills
    Author

    @James In hindsight I agree, The web app that I actually used this in was written by someone else I don’t have much control over it and they use tables, so I had to work with that. But I should of really changed the HTML for the tutorial.

  • http://www.freshivore.net Vince

    The article was not title “Semantics or Bust.”

    It was meant to show a click and drag effect.
    That being said:

    Tables for layout = terrible.

    Tables for tabular data? = excellent.

    When used correctly, I have about as much hate toward tables, as I do for a “dl” being used as a definition list…

    none.

  • Tim

    nice tut. i was confused at first, trying to drag the boxes.

  • Johan

    Nice to see some real plain javascript. All I see is JQuary tuts ;)

    Thx for this one!

  • Pingback: Leonaut.com

  • waqaszahoor

    Awesome Demo

  • http://msrgoal.blogspot.com Ranganathan

    This is really nice example for Drag selection. And explanation is very useful and simple.
    Nice!!

  • http://URL(Optional) Stevo

    Great facility. How do I send the results of the div cells back via a form?

  • http://evergreentr.com thejart

    wow, tables and inline js sure got a beating. here’s something a little more constructive…

    to keep the selected divs from toggling while dragging change the js like so:

    selectNum = 0;
    var originalbutton = true;
    var orignalstate = “”;

    function StartDragSelect(obj) {
    if (originalbutton) {
    originalstate = obj.className;
    originalbutton = false;
    }

    if (obj.className == “selected” && originalstate == “selected”) {
    obj.className = “”;
    selectNum–;
    }
    else if (obj.className == “” && originalstate == “”) {
    obj.className = “selected”;
    selectNum++;
    }
    document.getElementById(“selectCount”).innerHTML = selectNum;

    for(i=1;i<11;i++) {
    document.getElementById(i+’d').onmouseover = document.getElementById(i+’d').onmousedown
    }

    obj.onmouseup = function() {
    for(i=1;i<11;i++)
    {
    document.getElementById(i+’d').onmousedown = document.getElementById(i+’d').onmouseover;
    document.getElementById(i+’d').onmouseover = null;
    }
    originalbutton = true;
    }
    }

  • http://www.as7ap4you.com kareem

    this is wonderful tutorial i will put acopy of this lesson on
    my site here
    http://www.as7ap4you.com

  • Marti

    Double-clicking on a cell seems to break the functionality. :/

  • bj

    this doesn’t work with a table of text… since clicking and dragging will actually select the text… nasty.

  • Richard

    Anyway of taking the selected areas and say upon clicking submit it sends an email with the data?

    • Ron

      Would also like to know how to do that

  • Mahesh Kumar Chintawar

    wow….. it’s a gr8 source code…. I really need this for my project.
    Thank you very much.. it’s worth 1200$..

  • sh

    Great tutorial!
    Is there any further tutorial on how to get a ID-list of the selected div’s instead of counting it?

  • Vimard

    Hey, There’s a small bug here.. I was trying to do something similar to what you have done.. and then i found the same problem with your code too.. I don’t know how to fix it…

    Problem: Click the first tile.. don’t let go of the click.. move ur cursor to the left.. you will notice that ur mouse icon changes… When it changes let go of the mouse.. You will find that onmousemove() ur tiles are getting selected.

    P.S: Try it in firefox…

  • Adam

    Hi, I don’t want to be negative as I’m trying hard to learn javascript so really appreciate the time taken to produce these tutorials but what you show on the page differs in a couple of areas when I look at your source files, this does make it incredibly difficult to get a grasp of javascript when there are inconsistencies.

    An example is this -

    for(i=0;i<11;i++)
    {
    document.getElementById(i+'d').onmouseover = document.getElementById(i+'d').onmousedown
    }

    and in your source files you do not set i=0, instead only i=1.