jQuery clone html element dynamically on touchstart and then receive touchmove events

Viewed 134

I have some elements (widgets) in a div named tools. When I click on those elements I want to drag and drop them but not them directly. I clone the element in a new item named newnode and this is what I want to drag around the editor.

The trick that is working on desktop is to trigger an event on the new element, just $("#newnode").trigger(e);

$("#tools").on("mousedown touchstart",".widgets", function( e ) {
    InitialX=$(this).offset().left;
    InitialY=$(this).offset().top;
    $("#newnode").css("left",InitialX);
    $("#newnode").css("top",InitialY);
    $("#newnode").css("width",$(this).width());
    $("#newnode").css("height",$(this).height());
    $("#newnode>svg").html($($(this).find("g")[0]).clone());
    $("#newnode").show();
    $("#newnode").trigger(e);            
});

The code is working fine for desktop/computers but not for mobiles. When I send the trigger on desktop, the new cloned items start to receive events, being the new focused item, but when I do the same on mobiles tools/widget elements keeps receiving the events

I also added this code to see what was happening with the events, and yes, the old events is being sent to the non-cloned item.

$("#tools").on("blur focus focusin focusout load resize scroll unload click " +
"dblclick mousedown mouseup mousemove mouseover mouseout mouseenter " + 
 "mouseleave change select submit keydown keypress keyup error" +
 "touchstart touchend touchmove", ".widgets",function(e){
    console.log(e.type);
});

#newnode has z-index: 100000; to force to be over the original element.

to see an example on jsfiddle:

https://jsfiddle.net/hamboy75/v0br1cq6/44/

If you on computer, change to mobile in inspector, and you will see how it is different in log. Just click over a menu (duplicated will appear in gray color), without unclicking move a bit the mouse.

When viewed as computer newnode will receive events. When viewed as mobile widget will receive the events.

1 Answers

Finally i found a solution that works for my needs even if it is not exactly what i wanted (i wanted to receive all events in the new cloned item). Instead of adding the next line to receive the events in the #newnode element

$("#newnode").trigger(e);

i use the next code to receive events on #tools>.widgets, and if #newnode is visible resend the events to it using trigger.

$("#tools").on("mouseup mousedown mousemove touchstart touchend touchmove touchcancel", ".widgets",function(e){
     if($("#newnode").is(":visible"))
        $("#newnode").trigger(e);
});
Related