Search code examples
jqueryprimefacesdrag-and-dropjquery-ui-draggableprimefaces-datatable

Stop/Cancel Primefaces dragging action pressing Esc key


I want to be able to stop / cancel the dragging action once it has started, for example pressing Esc key. I'm working basing on a Primefaces Showcase example. https://www.primefaces.org/showcase/ui/dnd/dataTable.xhtml

<h:form id="carForm">
    <p:dataTable id="availableCars">
        <p:column>
            <h:outputText id="dragIcon" styleClass="ui-icon pi pi-plus"/>
            <p:draggable id="draggable" for="dragIcon" revert="true" helper="clone"/>
        </p:column>
    </p:dataTable>

    <p:outputPanel id="droppedArea">
        <!-- Here, there is a datatable where dragged rows are shown -->
        <p:dataTable id="selectedCars">
            ...
        </p:dataTable>
    </p:outputPanel>

    <p:droppable for="droppedArea" tolerance="touch" datasource="availableCars">
        <p:ajax listener="#{actionView.onDrop}" update="availableCars selectedCars" />
    </p:droppable>
</h:form>

In the keyup event, I have tried a lot of things to revert the drop event or even to send the event to a not dropped position. I also have tried to modify the PrimeFaces.widget.Droppable.prototype.bindDropListener function.

<script type="text/javascript">
    //detect Escape key press
    document.addEventListener("keyup", function(event) {
        if(event.keyCode === 27){
            $('.ui-draggable:data(draggable)').draggable( 'option',  'revert', true ).trigger( 'mouseup' );
        }
    });
</script>

Solution

  • So this is tricky and I had to use this myself to fix a bug in DataTable drop/drop. You have to get access to the Jquery Drag Drop Manager and cancel all events.

    var dragdrop = $.ui.ddmanager.current;
    if (dragdrop) {
        document.body.style.cursor = 'default';
        dragdrop.cancel();
    }