Make Elements On Your Site Draggable With Draggabilly.js

There’s a lot of tutorials out there on how to make things draggable in a web page. jQuery is one of the easiest ways. You don’t even need the jQuery UI, just a little help from the mouse direction function and perhaps some optional handling. But what if you don’t want to touch any jQuery code yet still want to make things draggable? Then, draggabilly.js is the right tool for you.

With Draggabilly.js, you can make any element on a web page draggable. You can customize the behavior of the draggable element like adding grid movement, binding event listeners to events, limiting the movements to only the x- or y-axis and much more. It also supports various browsers, IE8+ and even multi-touch mobile browsers.

Getting Started

To get started, you only need to include the Draggabilly.js source to your site. There isn’t a need for other dependencies. You can grab the file from GitHub.

 <script src="js/draggabilly.pkgd.min.js" type="text/javascript"></script> 

As for the rest, you’ll be working with some javascript function as per below.

Basic Dragging

You need to include the following snippet in your page so that the dragging can work.

 var elem = document.querySelector('#idHere'); var draggie = new Draggabilly( elem, { // options... }); 

The #idHere is the id you should put inside the HTML element you want to make draggable. While in the draggie variable, you can put in an option if you’d like. If you don’t need to have that option, you can also define the id from the elem variable.

For instance, if I have an id of #demo without any option, then I can write the snippet like so:

 var elem = document.querySelector('#demo'); var draggie = new Draggabilly('#demo'); 

Then inside the HTML, call the id of the element you wish turn draggable. The following is a basic example.

 <div class="demo-frame"> <div class="justDemo"> <div id="demo" class="relative"> <div class="centered">Drag me</div> </div> </div> </div> 

There are many other ways to affect Draggabilly’s behavior. You can restrict the dragging to be only in the ‘y’ or ‘x’ axis like so:

 new Draggabilly( '#demo', { axis: 'x' }); 

Or you can add a handling option, which will specifiy the starting element of the drag interaction like so:

 var elem = document.querySelector('#demo'); new Draggabilly( elem, { handle: '.handle' }); 

This .handle option is useful when all inner elements like inputs and forms don’t need to be draggable. There are still many other options you can add like containments, grids, methods and events. Head over to dragabbilly’s official homepage to see the full documentation.

Final Thought

The dragging feature, in most cases, has little effect on web design but it’s still pretty important. It takes place most often in web apps or games. The simplicity of its installation and the variety of different dragging methods makes this a really handy tool to try out.




via hongkiat.com http://ift.tt/1h6RwO0