joonis Logo

KSS Drag and Drop Plugin

This native HTML5 drag and drop plugin is supported by IE 7+, Firefox 3.5+, Safari 3.1+ (except 5.1), Chrome 3+ and Opera 12+. There exists also a plugin for the Yahoo drag/drop library.

Events

Dragged element

dragstart

Triggers when an element is started to be dragged. Similar to the event mousedown while initially moving the mouse.

  • evt-dragstart-effectallowed (default "all")

    This event parameter indicates which drop effect is allowed for the dragged item. Value can be one of "copy", "link", "move", "copyLink", "copyMove", "linkMove" or "all".

drag

Triggers when the mouse moves while dragging the element. Similar to the event mousemove.

dragend

Triggers at the end of a drag operation. Similar to the event mouseup.
Drop target element

dragenter

Triggers when a dragged element enters a drop target. Similar to the event mouseover.

dragover

Triggers when the mouse moves while dragging the element over a drop target. Similar to the event mousemove.

dragleave

Triggers when a dragged element leaves a drop target. Similar to the event mouseout.

drop

Triggers when a dragged element is dropped on a drop target. In this case the event dragleave is not triggered. Similar to the event mouseup.

Actions

setDropEffect

Sets the drop effect (default is "move"). This action is only available during the events dragenter and dragover. If set to "none" it is not possible to drop the element.

  • value: the effect to set (none, move, copy or link)

setDragImage

Sets the element that should be displayed near the mouse cursor. Uses the element given by kssSelector. This action is only available during the event dragstart. Unfortunatelly not supported by IE.

  • kssSelector: the element to set
  • offsetX: the horizontal offset in pixels (buggy in most browsers)
  • offsetY: the vertical offset in pixels (buggy in most browsers)

setDragData

Stores some data for the current dragging process. It can then be read by the dragData provider. This action is only available during the event dragstart.

  • type: the data type to set
  • value: the value to set

Parameter providers

dragData(datatype)

Reads the value of a given data type of the current dragging process that has been set by setDragData. This method is only available during the event drop.

Background

Whether a dragged item is droppable depends on the data types stored at the dragstart event (setDragData) and on the requested data types of the action that is going to be executed at a drop event (dragData). Provided that all requested data types are available, then the item will be considered as a droppable object.

During the events dragenter, dragover and dragleave there is a special state variable available named "validDropTarget". It is respectively set to "true" or "false" and can be used to customize the current drag operation (eg. highlight the drop target).

Examples

To be written...

ToDo

  • Try to emulate setDragImage in IE.
  • Try to fix offsetX and offsetY of setDragImage, because these parameters are buggy in Opera and Firefox.
  • Support of dragging and dropping files.

Code

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/*
    dnd_plugin.js - KSS Drag and Drop plugin

    Copyright (c) 2013, joonis new media
    Author: Thimo Kraemer <thimo.kraemer@joonis.de>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
    MA 02110-1301, USA.
*/


kukit.dnd = {
    _dropEffect: 'move',
    _isValidDropTarget: false,
    _dataTransfer: null
};

// A wrapper around the original dataTransfer object of a DND event.
// It enables the possibility to use any data type within the document,
// even if not supported by the browser (eg. IE<10).
kukit.dnd.DataTransfer = function() {

this.initialize = function(dataTransfer, external) {
    this.data = {};
    this.dataTransfer = dataTransfer;
    this.external = external || false;
    if (external) {
        // IE<10 doesn't provide the "types" attribute,
        // so we assume that we have a text and url value.
        // Anyway the only two supported types by IE<10.
        this.types = dataTransfer.types || ['text/plain', 'text/uri-list'];
    } else {
        this.types = [];
    }
};
this.normalizeType = function(type) {
    // Type mapping for backwards compatibility (IE<10)
    var map = {'text': 'text/plain', 'url': 'text/uri-list'};
    type = type.toLowerCase();
    return map[type] || type;
};
this.setData = function(type, value) {
    type = this.normalizeType(type);
    this.types.push(type);
    this.data[type] = value;
    // required by IE
    if (type == 'text/plain') {
        this.dataTransfer.setData('Text', value);
    } else if (type == 'text/uri-list') {
        this.dataTransfer.setData('url', value);
    }
    try {
        this.dataTransfer.setData(type, value);
    } catch (exc) {}
};
this.getData = function(type) {
    type = this.normalizeType(type);
    var value = this.data[type];
    if (!value) {
        // required by IE
        if (type == 'text/plain') {
            value = this.dataTransfer.getData('Text');
        } else if (type == 'text/uri-list') {
            value = this.dataTransfer.getData('url');
        }
    }
    if (!value) {
        try {
            value = this.dataTransfer.getData(type);
        } catch (exc) {}
    }
    return value || '';
};

this.initialize.apply(this, arguments);
};

kukit.dnd.isValidDropTarget = function(oper) {
    var dataTransfer = this._dataTransfer;
    if (!dataTransfer || this._dropEffect == 'none') {
        this._isValidDropTarget = false;
    } else if (oper) {
        // We want to know all required data types of each action that
        // is processed when an object is dropped. For that we evaluate
        // all parameter providers and pass an extra collector object.
        // The real job is then done by the parameter provider "dragData",
        // see below.
        var key, requiredDragData = [];
        var actions = oper.eventRule.actions.content;
        for (key in actions) {
            var action = actions[key];
            for (key in action.parms) {
                var param = action.parms[key];
                if (param.evaluate) {
                    param.evaluate(oper.node, {'_collector': requiredDragData});
                }
            }
        }
        // Now check if all requested data types are available.
        // Only in this case we declare it as a valid drop target.
        var isValid = true;
        for (var i=0; i<requiredDragData.length; i++) {
            isValid = false;
            var type = dataTransfer.normalizeType(requiredDragData[i]);
            for (var j=0; j<dataTransfer.types.length; j++) {
                if (dataTransfer.types[j] == type) {
                    isValid = true;
                    break;
                }
            }
            if (!isValid) {
                break;
            }
        }
        this._isValidDropTarget = isValid;
    }
    // Set it also as state variable.
    kukit.engine.stateVariables['validDropTarget'] = this._isValidDropTarget.toString();
    return this._isValidDropTarget;
};

// Main DND binder class
kukit.dnd.DNDEventBinder = function() {

this.__bind__ = function(oper, filter) {
;;; if (oper.node == null) {
;;;     throw new Error('DND event [' + oper.getEventName() + '] must be bound to a node.');
;;; }
;;; oper.componentName = 'DND event binding';
    oper.evaluateParameters([],
        {'preventdefault': '', 'allowbubbling': '', 'preventbubbling': ''},
        'dnd binder', true);
    oper.evalBool('preventdefault');
    oper.evalBool('allowbubbling');
    oper.evalBool('preventbubbling');
    // Register
    kukit.pl.registerBrowserEvent(oper, filter);
};

this.__bind_drag__ = function(opersByEventName) {
    var oper = opersByEventName.dragstart;
    if (oper) {
        // Make the node draggable if there exists a "dragstart" event.
        var node = oper.node;
        if (node.getAttribute('draggable') != 'true') {
            // HTML5 way
            node.setAttribute('draggable', 'true');
            node.style.cursor = 'default';
            try {
                // required by Safari
                node.style.webkitUserDrag = 'element';
                node.style.khtmlUserDrag = 'element';
            } catch (exc) {}
            if (node.dragDrop) {
                // required by IE<10
                kukit.ut.registerEventListener(node, 'selectstart', function(e) {
                    node.dragDrop();
                    e.preventDefault();
                });
            }
            // Default behaviour on dragstart event.
            // It must be executed before all others.
            kukit.ut.registerEventListener(node, 'dragstart', function(e) {
                if (node.getAttribute('draggable') != 'true') {
                    e.preventDefault();
                    return;
                }
                var effectallowed = oper.parms.effectallowed || 'all';
                // XXX Firefox through version 5 does not fire
                // the drop event if effectAllowed is set.
                e.dataTransfer.effectAllowed = effectallowed;
                // Create and store our own dataTransfer object
                kukit.dnd._dataTransfer = new kukit.dnd.DataTransfer(e.dataTransfer);
                try {
                    // required at least by Firefox
                    e.dataTransfer.setData('_dummy', '');
                } catch (exc) {}
            }, true);
            // Default behaviour on dragend event.
            kukit.ut.registerEventListener(node, 'dragend', function(e) {
                // Clear the dataTransfer object
                kukit.dnd._dataTransfer = null;
            });
        }
    }
    for (var name in opersByEventName) {
        this.__bind__(opersByEventName[name]);
    }
};

this.__bind_drop__ = function(opersByEventName) {
    var dnd = kukit.dnd;
    var oper = opersByEventName.drop;
    if (oper) {
        var node = oper.node;
        if (!node.getAttribute('droptarget')) {
            node.setAttribute('droptarget', 'true');
            // Default behaviour on drop event.
            kukit.ut.registerEventListener(node, 'drop', function(e) {
                // By default Firefox opens any transfered data as URL
                e.preventDefault();
            });
        }
        // Default behaviour on dragenter event.
        // It must be executed before all others.
        kukit.ut.registerEventListener(node, 'dragenter', function(e) {
            // We must renew the dataTransfer object on external drag actions
            if (!dnd._dataTransfer || dnd._dataTransfer.external) {
                dnd._dataTransfer = new dnd.DataTransfer(e.dataTransfer, true);
            }
            if (dnd.isValidDropTarget(oper)) {
                // Init drop effect
                dnd._dropEffect = e.dataTransfer.dropEffect = 'move';
                // Make the node a valid drop target
                e.preventDefault();
            }
        }, true);
        // Default behaviour on dragover event.
        kukit.ut.registerEventListener(node, 'dragover', function(e) {
            if (dnd.isValidDropTarget()) {
                // Apply drop effect
                e.dataTransfer.dropEffect = dnd._dropEffect;
                // Make the node a valid drop target
                e.preventDefault();
            }
        });
    }
    for (var name in opersByEventName) {
        this.__bind__(opersByEventName[name]); //, dnd.isValidDropTarget);
    }
};

};

kukit.eventsGlobalRegistry.registerForAllEvents(null,
    ['dragstart', 'drag', 'dragend'],
    kukit.dnd.DNDEventBinder, '__bind_drag__', null, 'Node');

kukit.eventsGlobalRegistry.registerForAllEvents(null,
    ['dragenter', 'dragover', 'dragleave', 'drop'],
    kukit.dnd.DNDEventBinder, '__bind_drop__', null, 'Node');



// action provider setDropEffect
kukit.actionsGlobalRegistry.register('setDropEffect', function(oper) {
    // value must be one of  none, move, copy or link
    oper.evaluateParameters(['value'], {});
    var type = oper.browserevent.type;
    if (type != 'dragenter' && type != 'dragover') {
;;;     kukit.E = 'Action provider setDropEffect is only available ';
;;;     kukit.E += 'during events [dragenter|dragover].';
;;;     throw new Error(kukit.E);
        return;
    }
    kukit.dnd._dropEffect = oper.parms.value.toLowerCase();
    // update validDropTarget state variable
    kukit.dnd.isValidDropTarget();
});


// action provider setDragImage, sets the element given by kssSelector
kukit.actionsGlobalRegistry.register('setDragImage', function(oper) {
    oper.evaluateParameters([], {offsetX: '0', offsetY: '0'});
    var event = oper.browserevent;
    if (event.type != 'dragstart') {
;;;     kukit.E = 'Action provider setDragImage is only available ';
;;;     kukit.E += 'during event [dragstart].';
;;;     throw new Error(kukit.E);
        return;
    }
    var parms = oper.parms;
    try {
        // Set the drag image. Not supported by IE.
        // Offsets are buggy in Opera and Firefox.
        event.dataTransfer.setDragImage(oper.node, parms.offsetX, parms.offsetY);
        // dataTransfer.addElement(elem) could be interesting, too.
        // But at time not supported by Safari and IE.
    } catch (exc) {}
});


// action provider setDragData
kukit.actionsGlobalRegistry.register('setDragData', function(oper) {
    oper.evaluateParameters(['type', 'value'], {});
    if (oper.browserevent.type != 'dragstart') {
;;;     kukit.E = 'Action provider setDragData is only available ';
;;;     kukit.E += 'during event [dragstart].';
;;;     throw new Error(kukit.E);
        return;
    }
    var dataTransfer = kukit.dnd._dataTransfer;
    if (!dataTransfer) {
;;;     kukit.E = 'No dataTransfer object available.';
;;;     throw new Error(kukit.E);
        return;
    }
    var parms = oper.parms;
    dataTransfer.setData(parms.type, parms.value);
});


// parameter provider dragData
kukit.pprovidersGlobalRegistry.register('dragData', function() {

this.check = function(args) {
;;; if (args.length != 1) {
;;;     throw new Error('dragData method needs exactly 1 argument [datatype].');
;;; }
};

this.eval = function(args, node, defaultParameters) {
    // Check if we just want to collect all requested data types.
    // Used by kukit.dnd.DNDEventBinder.isValidDropTarged above.
    if (defaultParameters && defaultParameters._collector) {
        defaultParameters._collector.push(args[0]);
        return '';
    }
    var dataTransfer = kukit.dnd._dataTransfer;
    if (!dataTransfer) {
;;;     kukit.E = 'No dataTransfer object available.';
;;;     throw new Error(kukit.E);
        return;
    }
    return dataTransfer.getData(args[0]);
};

});

Kann ich
  Ihnen helfen?


Schreiben Sie mir
doch einfach unter
giraffe@joonis.de