Giter Site home page Giter Site logo

sortablejs / sortable Goto Github PK

View Code? Open in Web Editor NEW
28.7K 413.0 3.7K 2.53 MB

Reorderable drag-and-drop lists for modern browsers and touch devices. No jQuery or framework required.

Home Page: https://sortablejs.github.io/Sortable/

License: MIT License

JavaScript 95.41% CSS 0.80% HTML 3.78%
drag sortable reordering sort drag-and-drop drag-drop ui draggable droppable touch

sortable's Introduction

Sortable   Financial Contributors on Open Collective CircleCI DeepScan grade npm

Sortable is a JavaScript library for reorderable drag-and-drop lists.

Demo: http://sortablejs.github.io/Sortable/

Features

  • Supports touch devices and modern browsers (including IE9)
  • Can drag from one list to another or within the same list
  • CSS animation when moving items
  • Supports drag handles and selectable text (better than voidberg's html5sortable)
  • Smart auto-scrolling
  • Advanced swap detection
  • Smooth animations
  • Multi-drag support
  • Support for CSS transforms
  • Built using native HTML5 drag and drop API
  • Supports
  • Supports any CSS library, e.g. Bootstrap
  • Simple API
  • Support for plugins
  • CDN
  • No jQuery required (but there is support)
  • Typescript definitions at @types/sortablejs

Articles


Getting Started

Install with NPM:

npm install sortablejs --save

Install with Bower:

bower install --save sortablejs

Import into your project:

// Default SortableJS
import Sortable from 'sortablejs';

// Core SortableJS (without default plugins)
import Sortable from 'sortablejs/modular/sortable.core.esm.js';

// Complete SortableJS (with all plugins)
import Sortable from 'sortablejs/modular/sortable.complete.esm.js';

Cherrypick plugins:

// Cherrypick extra plugins
import Sortable, { MultiDrag, Swap } from 'sortablejs';

Sortable.mount(new MultiDrag(), new Swap());


// Cherrypick default plugins
import Sortable, { AutoScroll } from 'sortablejs/modular/sortable.core.esm.js';

Sortable.mount(new AutoScroll());

Usage

<ul id="items">
	<li>item 1</li>
	<li>item 2</li>
	<li>item 3</li>
</ul>
var el = document.getElementById('items');
var sortable = Sortable.create(el);

You can use any element for the list and its elements, not just ul/li. Here is an example with divs.


Options

var sortable = new Sortable(el, {
	group: "name",  // or { name: "...", pull: [true, false, 'clone', array], put: [true, false, array] }
	sort: true,  // sorting inside list
	delay: 0, // time in milliseconds to define when the sorting should start
	delayOnTouchOnly: false, // only delay if user is using touch
	touchStartThreshold: 0, // px, how many pixels the point should move before cancelling a delayed drag event
	disabled: false, // Disables the sortable if set to true.
	store: null,  // @see Store
	animation: 150,  // ms, animation speed moving items when sorting, `0` — without animation
	easing: "cubic-bezier(1, 0, 0, 1)", // Easing for animation. Defaults to null. See https://easings.net/ for examples.
	handle: ".my-handle",  // Drag handle selector within list items
	filter: ".ignore-elements",  // Selectors that do not lead to dragging (String or Function)
	preventOnFilter: true, // Call `event.preventDefault()` when triggered `filter`
	draggable: ".item",  // Specifies which items inside the element should be draggable

	dataIdAttr: 'data-id', // HTML attribute that is used by the `toArray()` method

	ghostClass: "sortable-ghost",  // Class name for the drop placeholder
	chosenClass: "sortable-chosen",  // Class name for the chosen item
	dragClass: "sortable-drag",  // Class name for the dragging item

	swapThreshold: 1, // Threshold of the swap zone
	invertSwap: false, // Will always use inverted swap zone if set to true
	invertedSwapThreshold: 1, // Threshold of the inverted swap zone (will be set to swapThreshold value by default)
	direction: 'horizontal', // Direction of Sortable (will be detected automatically if not given)

	forceFallback: false,  // ignore the HTML5 DnD behaviour and force the fallback to kick in

	fallbackClass: "sortable-fallback",  // Class name for the cloned DOM Element when using forceFallback
	fallbackOnBody: false,  // Appends the cloned DOM Element into the Document's Body
	fallbackTolerance: 0, // Specify in pixels how far the mouse should move before it's considered as a drag.

	dragoverBubble: false,
	removeCloneOnHide: true, // Remove the clone element when it is not showing, rather than just hiding it
	emptyInsertThreshold: 5, // px, distance mouse must be from empty sortable to insert drag element into it


	setData: function (/** DataTransfer */dataTransfer, /** HTMLElement*/dragEl) {
		dataTransfer.setData('Text', dragEl.textContent); // `dataTransfer` object of HTML5 DragEvent
	},

	// Element is chosen
	onChoose: function (/**Event*/evt) {
		evt.oldIndex;  // element index within parent
	},

	// Element is unchosen
	onUnchoose: function(/**Event*/evt) {
		// same properties as onEnd
	},

	// Element dragging started
	onStart: function (/**Event*/evt) {
		evt.oldIndex;  // element index within parent
	},

	// Element dragging ended
	onEnd: function (/**Event*/evt) {
		var itemEl = evt.item;  // dragged HTMLElement
		evt.to;    // target list
		evt.from;  // previous list
		evt.oldIndex;  // element's old index within old parent
		evt.newIndex;  // element's new index within new parent
		evt.oldDraggableIndex; // element's old index within old parent, only counting draggable elements
		evt.newDraggableIndex; // element's new index within new parent, only counting draggable elements
		evt.clone // the clone element
		evt.pullMode;  // when item is in another sortable: `"clone"` if cloning, `true` if moving
	},

	// Element is dropped into the list from another list
	onAdd: function (/**Event*/evt) {
		// same properties as onEnd
	},

	// Changed sorting within list
	onUpdate: function (/**Event*/evt) {
		// same properties as onEnd
	},

	// Called by any change to the list (add / update / remove)
	onSort: function (/**Event*/evt) {
		// same properties as onEnd
	},

	// Element is removed from the list into another list
	onRemove: function (/**Event*/evt) {
		// same properties as onEnd
	},

	// Attempt to drag a filtered element
	onFilter: function (/**Event*/evt) {
		var itemEl = evt.item;  // HTMLElement receiving the `mousedown|tapstart` event.
	},

	// Event when you move an item in the list or between lists
	onMove: function (/**Event*/evt, /**Event*/originalEvent) {
		// Example: https://jsbin.com/nawahef/edit?js,output
		evt.dragged; // dragged HTMLElement
		evt.draggedRect; // DOMRect {left, top, right, bottom}
		evt.related; // HTMLElement on which have guided
		evt.relatedRect; // DOMRect
		evt.willInsertAfter; // Boolean that is true if Sortable will insert drag element after target by default
		originalEvent.clientY; // mouse position
		// return false; — for cancel
		// return -1; — insert before target
		// return 1; — insert after target
		// return true; — keep default insertion point based on the direction
		// return void; — keep default insertion point based on the direction
	},

	// Called when creating a clone of element
	onClone: function (/**Event*/evt) {
		var origEl = evt.item;
		var cloneEl = evt.clone;
	},

	// Called when dragging element changes position
	onChange: function(/**Event*/evt) {
		evt.newIndex // most likely why this event is used is to get the dragging element's current index
		// same properties as onEnd
	}
});

group option

To drag elements from one list into another, both lists must have the same group value. You can also define whether lists can give away, give and keep a copy (clone), and receive elements.

  • name: String — group name
  • pull: true|false|["foo", "bar"]|'clone'|function — ability to move from the list. clone — copy the item, rather than move. Or an array of group names which the elements may be put in. Defaults to true.
  • put: true|false|["baz", "qux"]|function — whether elements can be added from other lists, or an array of group names from which elements can be added.
  • revertClone: boolean — revert cloned element to initial position after moving to a another list.

Demo:


sort option

Allow sorting inside list.

Demo: https://jsbin.com/jayedig/edit?js,output


delay option

Time in milliseconds to define when the sorting should start. Unfortunately, due to browser restrictions, delaying is not possible on IE or Edge with native drag & drop.

Demo: https://jsbin.com/zosiwah/edit?js,output


delayOnTouchOnly option

Whether or not the delay should be applied only if the user is using touch (eg. on a mobile device). No delay will be applied in any other case. Defaults to false.


swapThreshold option

Percentage of the target that the swap zone will take up, as a float between 0 and 1.

Read more

Demo: http://sortablejs.github.io/Sortable#thresholds


invertSwap option

Set to true to set the swap zone to the sides of the target, for the effect of sorting "in between" items.

Read more

Demo: http://sortablejs.github.io/Sortable#thresholds


invertedSwapThreshold option

Percentage of the target that the inverted swap zone will take up, as a float between 0 and 1. If not given, will default to swapThreshold.

Read more


direction option

Direction that the Sortable should sort in. Can be set to 'vertical', 'horizontal', or a function, which will be called whenever a target is dragged over. Must return 'vertical' or 'horizontal'.

Read more

Example of direction detection for vertical list that includes full column and half column elements:

Sortable.create(el, {
	direction: function(evt, target, dragEl) {
		if (target !== null && target.className.includes('half-column') && dragEl.className.includes('half-column')) {
			return 'horizontal';
		}
		return 'vertical';
	}
});

touchStartThreshold option

This option is similar to fallbackTolerance option.

When the delay option is set, some phones with very sensitive touch displays like the Samsung Galaxy S8 will fire unwanted touchmove events even when your finger is not moving, resulting in the sort not triggering.

This option sets the minimum pointer movement that must occur before the delayed sorting is cancelled.

Values between 3 to 5 are good.


disabled options

Disables the sortable if set to true.

Demo: https://jsbin.com/sewokud/edit?js,output

var sortable = Sortable.create(list);

document.getElementById("switcher").onclick = function () {
	var state = sortable.option("disabled"); // get

	sortable.option("disabled", !state); // set
};

handle option

To make list items draggable, Sortable disables text selection by the user. That's not always desirable. To allow text selection, define a drag handler, which is an area of every list element that allows it to be dragged around.

Demo: https://jsbin.com/numakuh/edit?html,js,output

Sortable.create(el, {
	handle: ".my-handle"
});
<ul>
	<li><span class="my-handle">::</span> list item text one
	<li><span class="my-handle">::</span> list item text two
</ul>
.my-handle {
	cursor: move;
	cursor: -webkit-grabbing;
}

filter option

Sortable.create(list, {
	filter: ".js-remove, .js-edit",
	onFilter: function (evt) {
		var item = evt.item,
			ctrl = evt.target;

		if (Sortable.utils.is(ctrl, ".js-remove")) {  // Click on remove button
			item.parentNode.removeChild(item); // remove sortable item
		}
		else if (Sortable.utils.is(ctrl, ".js-edit")) {  // Click on edit link
			// ...
		}
	}
})

ghostClass option

Class name for the drop placeholder (default sortable-ghost).

Demo: https://jsbin.com/henuyiw/edit?css,js,output

.ghost {
  opacity: 0.4;
}
Sortable.create(list, {
  ghostClass: "ghost"
});

chosenClass option

Class name for the chosen item (default sortable-chosen).

Demo: https://jsbin.com/hoqufox/edit?css,js,output

.chosen {
  color: #fff;
  background-color: #c00;
}
Sortable.create(list, {
  delay: 500,
  chosenClass: "chosen"
});

forceFallback option

If set to true, the Fallback for non HTML5 Browser will be used, even if we are using an HTML5 Browser. This gives us the possibility to test the behaviour for older Browsers even in newer Browser, or make the Drag 'n Drop feel more consistent between Desktop , Mobile and old Browsers.

On top of that, the Fallback always generates a copy of that DOM Element and appends the class fallbackClass defined in the options. This behaviour controls the look of this 'dragged' Element.

Demo: https://jsbin.com/sibiput/edit?html,css,js,output


fallbackTolerance option

Emulates the native drag threshold. Specify in pixels how far the mouse should move before it's considered as a drag. Useful if the items are also clickable like in a list of links.

When the user clicks inside a sortable element, it's not uncommon for your hand to move a little between the time you press and the time you release. Dragging only starts if you move the pointer past a certain tolerance, so that you don't accidentally start dragging every time you click.

3 to 5 are probably good values.


dragoverBubble option

If set to true, the dragover event will bubble to parent sortables. Works on both fallback and native dragover event. By default, it is false, but Sortable will only stop bubbling the event once the element has been inserted into a parent Sortable, or can be inserted into a parent Sortable, but isn't at that specific time (due to animation, etc).

Since 1.8.0, you will probably want to leave this option as false. Before 1.8.0, it may need to be true for nested sortables to work.


removeCloneOnHide option

If set to false, the clone is hidden by having it's CSS display property set to none. By default, this option is true, meaning Sortable will remove the cloned element from the DOM when it is supposed to be hidden.


emptyInsertThreshold option

The distance (in pixels) the mouse must be from an empty sortable while dragging for the drag element to be inserted into that sortable. Defaults to 5. Set to 0 to disable this feature.

Demo: https://jsbin.com/becavoj/edit?js,output

An alternative to this option would be to set a padding on your list when it is empty.

For example:

ul:empty {
  padding-bottom: 20px;
}

Warning: For :empty to work, it must have no node inside (even text one).

Demo: https://jsbin.com/yunakeg/edit?html,css,js,output


Event object (demo)

  • to:HTMLElement — list, in which moved element
  • from:HTMLElement — previous list
  • item:HTMLElement — dragged element
  • clone:HTMLElement
  • oldIndex:Number|undefined — old index within parent
  • newIndex:Number|undefined — new index within parent
  • oldDraggableIndex: Number|undefined — old index within parent, only counting draggable elements
  • newDraggableIndex: Number|undefined — new index within parent, only counting draggable elements
  • pullMode:String|Boolean|undefined — Pull mode if dragging into another sortable ("clone", true, or false), otherwise undefined

move event object

  • to:HTMLElement
  • from:HTMLElement
  • dragged:HTMLElement
  • draggedRect:DOMRect
  • related:HTMLElement — element on which have guided
  • relatedRect:DOMRect
  • willInsertAfter:Booleantrue if will element be inserted after target (or false if before)

Methods

option(name:String[, value:*]):*

Get or set the option.

closest(el:HTMLElement[, selector:String]):HTMLElement|null

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

toArray():String[]

Serializes the sortable's item data-id's (dataIdAttr option) into an array of string.

sort(order:String[], useAnimation:Boolean)

Sorts the elements according to the array.

var order = sortable.toArray();
sortable.sort(order.reverse(), true); // apply
save()

Save the current sorting (see store)

destroy()

Removes the sortable functionality completely.


Store

Saving and restoring of the sort.

<ul>
	<li data-id="1">order</li>
	<li data-id="2">save</li>
	<li data-id="3">restore</li>
</ul>
Sortable.create(el, {
	group: "localStorage-example",
	store: {
		/**
		 * Get the order of elements. Called once during initialization.
		 * @param   {Sortable}  sortable
		 * @returns {Array}
		 */
		get: function (sortable) {
			var order = localStorage.getItem(sortable.options.group.name);
			return order ? order.split('|') : [];
		},

		/**
		 * Save the order of elements. Called onEnd (when the item is dropped).
		 * @param {Sortable}  sortable
		 */
		set: function (sortable) {
			var order = sortable.toArray();
			localStorage.setItem(sortable.options.group.name, order.join('|'));
		}
	}
})

Bootstrap

Demo: https://jsbin.com/visimub/edit?html,js,output

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>


<!-- Latest Sortable -->
<script src="http://SortableJS.github.io/Sortable/Sortable.js"></script>


<!-- Simple List -->
<ul id="simpleList" class="list-group">
	<li class="list-group-item">This is <a href="http://SortableJS.github.io/Sortable/">Sortable</a></li>
	<li class="list-group-item">It works with Bootstrap...</li>
	<li class="list-group-item">...out of the box.</li>
	<li class="list-group-item">It has support for touch devices.</li>
	<li class="list-group-item">Just drag some elements around.</li>
</ul>

<script>
    // Simple list
    Sortable.create(simpleList, { /* options */ });
</script>

Static methods & properties

Sortable.create(el:HTMLElement[, options:Object]):Sortable

Create new instance.


Sortable.active:Sortable

The active Sortable instance.


Sortable.dragged:HTMLElement

The element being dragged.


Sortable.ghost:HTMLElement

The ghost element.


Sortable.clone:HTMLElement

The clone element.


Sortable.get(element:HTMLElement):Sortable

Get the Sortable instance on an element.


Sortable.mount(plugin:...SortablePlugin|SortablePlugin[])

Mounts a plugin to Sortable.


Sortable.utils
  • on(el:HTMLElement, event:String, fn:Function) — attach an event handler function
  • off(el:HTMLElement, event:String, fn:Function) — remove an event handler
  • css(el:HTMLElement):Object — get the values of all the CSS properties
  • css(el:HTMLElement, prop:String):Mixed — get the value of style properties
  • css(el:HTMLElement, prop:String, value:String) — set one CSS properties
  • css(el:HTMLElement, props:Object) — set more CSS properties
  • find(ctx:HTMLElement, tagName:String[, iterator:Function]):Array — get elements by tag name
  • bind(ctx:Mixed, fn:Function):Function — Takes a function and returns a new one that will always have a particular context
  • is(el:HTMLElement, selector:String):Boolean — check the current matched set of elements against a selector
  • closest(el:HTMLElement, selector:String[, ctx:HTMLElement]):HTMLElement|Null — for each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree
  • clone(el:HTMLElement):HTMLElement — create a deep copy of the set of matched elements
  • toggleClass(el:HTMLElement, name:String, state:Boolean) — add or remove one classes from each element
  • detectDirection(el:HTMLElement):String — automatically detect the direction of the element as either 'vertical' or 'horizontal'
  • index(el:HTMLElement, selector:String):Number — index of the element within its parent for a selected set of elements
  • getChild(el:HTMLElement, childNum:Number, options:Object, includeDragEl:Boolean):HTMLElement — get the draggable element at a given index of draggable elements within a Sortable instance
  • expando:String — expando property name for internal use, sortableListElement[expando] returns the Sortable instance of that elemenet

Plugins

Extra Plugins (included in complete versions)

Default Plugins (included in default versions)


CDN

<!-- jsDelivr :: Sortable :: Latest (https://www.jsdelivr.com/package/npm/sortablejs) -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>

Contributing (Issue/PR)

Please, read this.


Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

MIT LICENSE

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

sortable's People

Contributors

2xaa avatar amfleming avatar camargo avatar caub avatar code4fan avatar dandv avatar dapetcu21 avatar davewood avatar david-desmaisons avatar dev101 avatar driskull avatar fendy3002 avatar gravypower avatar gutenye avatar joey-becker avatar kalaspuffar avatar korsar-zn avatar markmarkoh avatar noelheesen avatar owen-m1 avatar rubaxa avatar sdesapio avatar slawekkaczorowski avatar sp-kilobug avatar srosengren avatar timvdlippe avatar varunkumar avatar waynevanson avatar why520crazy avatar ziflex avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sortable's Issues

Mobile Sorting an Ordered List

First of all great light weight implementation!
Everything is working great so far, I have an ordered list for a web / mobile app.

The list is numbered
1
2
3
4
5

When I go to move the order of an item it will display the number 6 while I am moving it , this is not an issue on the web side only on mobile.

Any thoughts?

Is this a bug or is there another way to approach the implementation on my part?

Slow in Chrome when many elements in the page

Try this test in Chrome: http://jsbin.com/nizag/1/edit
(You might need to press the "Run with JS" button in jsbin.)

Sortable was only applied to the first 30 elements. If you try dragging/sorting elements in this first group, you will notice the poor performance. This is only the case in Chrome. Safari and Firefox performed well in my tests.

My guess is that one of the events binded to document might be causing it.

_closest

There's a small error in it that if ctx is undefined it does nothing.

if( el && ctx){

really should be...

if( el ){

...since your defining ctx on the next line anyway.

Also, if you care about speed how about using matches/matchSelector, its alot faster.....
http://jsperf.com/closestagain
...and according to caniuse available in all modern browser except Opera Mini.

Oh, and thanks for making this, Ive looked a few times for something like this that doesnt use JQuery and this is the first thing thats ever popped up....well done.

EDIT: Actually I take the speed thing back as I just tested it in FF and yours won. I have a bad habit of only testing in Chrome because its the only browser I code for.

Loading via RequireJS

Downloaded your library via Bower and am trying to load it using RequireJS yet am getting

Uncaught ReferenceError: Sortable is not defined

Using with bootstrap tables, alerts twice!!

Hi, great plugin. When I use it with bootstrap 3 table, I am giving .sortable class tbody, because I want it to be sorted by rows.

 $('.sortable').sortable().bind('sortupdate', function() {
    alert('dragged');
});

When I sort one item, it alerts twice. Any idea or does it cause any trouble. I am considering an ajax call on sortupdate.

Saving the sorted position in some way

Hey I love the plugin it works perfectly for my requirements.
But i needed a way to save the positions of the particular items moved eg: a widget on dashboard, like they don't reset back to the original position on a reload
Is it possible to the save position in a cookie or a database for that matter any help would be deeply appreciated. Thanks
PS : i'm working on a project that has a user session with a dashboard and a lot of analytical widgets.

Make this available on bower

It would be great if this was available on bower, the package manager for frontend projects. All that is needed is a bower.json file and for the project to be registered in the bower repository.

In a bower package it is usual to contain both the source and the minified files.

Sortable doesn't work on IE9

Just tested on http://rubaxa.github.io/Sortable/

For some reason, all I seem to be able to do is select text, which is weird because I see you disable user.select. It did work once, but not properly, the other items did not rearrange and I was only able to move the draggable one position. It also logged '''LOG: onUpdate.foo:[object HTMLLIElement]''' but after that I had no more success.

I also tried v1.8 and v1.5 on jsfiddle but with the same results.

IE9 is supported right? It has partial support on caniuse and I see that in your code you explicitly declare things for IE9. Thanks!

//edit: weirdly, the images in the "multi" section appear to work properly, however, no draggable is visible.

Browser Support

Is it possible to add info about which browsers does this work in and has been tested?

draggable container

Наверно не следует инициализировать ноду ( https://github.com/RubaXa/Sortable/blob/master/Sortable.js#L132 ), если она такого же типа как и тягаемые элементы и не указан селектор для них в параметрах. Иначе тягаемые элементы рушат контейнер.

Не нужно инициализировать контейнер в таком примере:

<div id=container>
 <div>el1</div>
 <div>el1</div>
</div>

В _closest нужно возвращать null до цикла.

А можете пояснить что за магия тут происходит?
https://github.com/RubaXa/Sortable/blob/master/Sortable.js#L403-L411

v0.4 tag

Is v0.4 officially released? If so, please push a tag so bower recognizes it.

Thanks!

"Store" not possible when using html-code in div/li-element

Hello,

I have the following problem: When trying to use links in a sortable element, it messes up the whole order of the elements when reloading. It seems, that the store-function doesn't work with links. I used the same code as in the Readme with a few elements like this:
<li class="google" draggable="true"><a href="http://google.com">Google</a></li>
I already tried to use div-elements instead, but this didn't work either.

Everything else works perfectly fine!

Best regards and thanks for your help.

Pfahli

Extrange behavior on not empty and not full containers

I have a N colums table with a lot of divs on this columns, when i try to move one div from one column to another I need to put it near of and existing div, if i put it on the free space of the column, don't works. 😞

AutoScroll when drag anything to the border of the viewport

When I try to sort a big sortable list (or move from one list to another), sometimes i need to scroll, is posible to add an autoscroll option (disabled by default if you want).

I can implement it, if you want, and send you a pull-request.

"data-force" attributes

This is not a real issue, sorry...
I just want to ask whats' the meaning of "data-force" attributes in example html...

Current version breaks IE versions 10 & 11

As far as i could debug, the _onTouchMove is bound to the pointermove event.
In line 246 the IE throws the exceptions when trying to acces touch = evt.touches[0] and touches is undefined as im in the browser.

Events

Heya! Looks like there is a bug in the events for adding items.
srcElement and target are set to item.

remove:

item: li.link-item
srcElement: ul.columns.list-unstyled
target: ul.columns.list-unstyled
type: "remove"

add:

item: li.link-item
srcElement: li.link-item
target: li.link-item
type: "add"

Thanks for a very nice library! Works sweet on Android and Chrome, FF and iE10 on Windows. Do you know if it works without workarounds on Apple/iOS?

Option to avoid dragging back

Hi!

Thank you for you great plugin!
I have two groups/columns of items which are draggable one into other. I need to prohibit dragging the element back or to set disable status for some group/column so you cannot drop there items.
I don't find it in your plugin and I doubt what to do: to modify code of your plugin manually or maybe to wait the update with this option ;-)

Best regards,
Tetyana, Ukraine

Styling the currently dragged element

I can style the ghost of the currently dragged element via the class .sortable-ghost but how about the currently dragged element itself?
I would like to add a shadow to it.

Items are drag-able but indexes remain the same.

As the title says, the directive seems to be working fine as I can drag and move the items but once I look at the indexes they always show the same initial order.

Which is a problem seeing as the way I remember the new order the user created by dragging and dropping is by sending the indexes to the server, but seeing as the indexes never change the order remains the same as it initially was.

Browser: Chrome(latest),Firefox(25)
OS:Ubuntu
Angular: 1.2.x

Option for delay

Hi Konstantin, great job.
A good improvement would be the introduction of an option for a custom delay between the first touch and the sorting action. This is needed when the sortable list fits the with of the screen on mobile devices, and Sortable prevents the normal scrolling behaviour (touching the screen to scroll drags the touched list entry instead). This could be avoided with a 500ms delay before enabling sorting.

Error when sorting

Uncaught TypeError: Object #<HTMLDivElement> has no method 'dragDrop'

I get this error when i start sorting the objects.. Both in chrome and safari..
Seems like the error comes from this code:

// IE 9 Support
if( target && evt.type == 'selectstart' ){
  if( target.tagName != 'A' && target.tagName != 'IMG'){
    target.dragDrop();
  }
}

SVG elements

Sorting SVG elements does not behave as expected. For instance, in Chrome 34.0.1847.116, el.className returns an object, not a string as for HTML elements. This is due to SVG's handling of animations.

As a result, functions, such as _closest(el, selector, ctx), do not affect/return the selected element.

I made a quick few hacks to try and make this work, but to no avail. For instance,

/**
* FUNCTION: _closest( el, selector, ctx )
*   Finds the closest DOMElement specified as draggable.
*
* @param {DOMElement} el - DOM element
* @param {string} selector - CSS class selector; e.g., .item or li.item
* @param {DOMElement} ctx - context of the element event
* @returns {DOMElement} if no element is found, returns null
*/
function _closest( el, selector, ctx ){
    var className;

    if ( "*" === selector ) {
        return el;
    }

        if ( el ) {

            ctx = ctx || y, selector = selector.split(".");

            var tag = selector.shift().toUpperCase(),
                re = new RegExp("\\s(" + selector.join("|") + ")\\s", "g");

            do {

                // SVG Hack:
                className = el.className;

                if ( className.hasOwnProperty && className.hasOwnProperty( 'baseVal' ) ) {
                    className = className.baseVal;
                }

                if (!("" !== tag && el.nodeName != tag || selector.length && ((" " + className + " ").match(re) || []).length != selector.length)) {
                    return el;
                }
            } while (el !== ctx && (el = el.parentNode));
        }

        return null;

} // end FUNCTION _closest()

The change works for the demo and does return SVG elements, but the drag listeners are never fired, it seems. I forked and included the edits, but cannot seem to get it working.

Any thoughts?

Изменение html перетаскиваемого элемента

Не могу разобраться, каким образом можно менять html перетаскиваемого элемента. К примеру, есть два списка, и при перемещении из одного в другой во время размещения текущего элемента над другим списком нужно поменять его форму. Существует способ как это можно сделать?

Parallax effect on demo page affects performance, causes confusion, looks bad

The parallax effect on the demo page is a source of confusion and affects performance.

See the thread on reddit where users said:

I puked a little on my keyboard.

Oh it was intentional parallax? I was thinking it was some sort of bug.

It adds nothing to the site, it just makes it harder to use, and annoys the hell out of me.

<marquee><blink>What's wrong with the parallax effect?</blink></marquee>

Реакция на мышку

При движении мышки по экрану элементы страницы движутся. Это так задумано или баг? Выглядит как то глючно.
При перетаскивании, если элемент отпускать не в верхней правой части, а например в нижнем правом, левом или левом верхнем углу, то он не перетаскивается, а возвращается в исходную позицию. Приходится тянуть несколько раз, чтоб угадать где его отпустить, или дотягивать до середины блока.

Nested list

Hey! This plugin looks awesome, but I noticed that there is no support for nested lists. Or did I miss this? If not, will this featured be added soon, or is it something I do not have to expect in the near future?

How to make draggable "composite" elements?

Is it possible to make draggable "composite" elements?
I.e: I have an element in a group, which is not a single , but a div with an img and a text label below...
Trying to change with

...
works with the first drag, but then you can't drag it anymore... :-(
What do I miss?

Saving order

Hey. I wonder, is there any way how to get an array which contains an order of elements in my sortable list? Something like toArray method. Then, I would be able to store the order permanently within user cookies or using Web Storage. Thanks.

CSS селектор draggable элементов должен учитывать '-' разделитель внутри классов

Разметка draggable элемента в листе такого рода:

<div class='drag'>
   <div class='drag-child-one'></div>
   <div class='drag-child-two'></div>
</div>

Делаю Sortable:

new Sortable(TaskListContainer, {
        handle: ".drag"
    });

И соотвественно хочу чтобы таскался только drag элемент.
Но draggable становятся и оба child`а, что не нужно.

https://github.com/RubaXa/Sortable/blob/master/Sortable.js#L400
Предлагаю RegExp селектора _closest сделать примеро так:
new RegExp('\b('+selector.join('|')+')(?!-)\b', 'g')

Problems when one of the lists is empty

Hi!

This is a great sorting script, I am enjoying the efficiency so far.

One problem I've run into is when I start out with one of the groups being empty. For example if I want to add items from one list to another and the second list is empty, I am able to only move one item and after that the script just quietly stops functioning for some reason.

No errors are displayed so I don't understand what the problem is.

Here's a JS fiddle with the scenario I'm talking about (the second group is empty at start): http://jsfiddle.net/msurguy/tQ6FL/

Browser support?

Will this work in IE8, or is IE9 the oldest supported?

Edit: It seems it doesn't work with IE8 even with es5 shim, es5 sham, and addEventListener polyfills. I managed to get rid of all errors, but also all functionality is seems :-)

If you don't feel like looking into IE8 issues, I completely understand. If you do, very much appreciated!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.