Search code examples
javascriptjquerydrag-and-dropaloha-editor

How to get a range object that correspond to the position of a drop event?


I want to drag and drop images into an aloha editable field.

I am looking at the at.tapo.aloha.plugins.Image plugin which seems great.

However, i need to adapt this plugin in order to work with thumbnail. I drag the thumbnail and when I drop it into the aloha editable, the html code is modified on the fly in order to use the real image.

    GENTICS.Aloha.EventRegistry.subscribe(GENTICS.Aloha, 'editableCreated', function(event, editable) {
        var the_obj = editable.obj;
        jQuery(editable.obj).bind('drop', function(event){
            var e = event.originalEvent;
            var files = e.dataTransfer.files;
            var count = files.length;

            if (count < 1) {
                var node = e.dataTransfer.mozSourceNode;
                if (node.tagName === 'IMG') {
                    var html = '<img ....>'; //build the real image html code  
                    /// The current selection but I want the drop position
                    var range = GENTICS.Aloha.Selection.getRangeObject();
                    if (!jQuery.isEmptyObject(range)) {
                        GENTICS.Utils.Dom.insertIntoDOM(jQuery(html), range, the_obj);
                    }
                    return false;
                }
                return true;
            }
    }

It works ok when something is selected in the aloha field. I can get a range and insert the html into the DOM at the selection position.

However, I would like to get a range object that correspond to the place where my image is dropped. How to do that?

Thanks in advance for ideas.


Solution

  • There isn't an easy way that I know of to do this in general. You could obtain pixel coordinates for the drop point (possibly from a mousemove event) and then attempt to get a range for that point. For that task, the answer to the following question sums it up nicely:

    Creating a collapsed range from a pixel position in FF/Webkit