Trigger JavaScript event on different target

210 Views Asked by At

I have a element which adds a child to itself when a mousedown or touchstart event occurs. This child is resizable (jQuery ui widget). I use http://touchpunch.furf.com/ which enables jquery-ui widgets for touch devices.

I want to resize the child when it gets created without lifting the mouse/touch and clicking again. It works for mouse devices but I fail to trigger it when using a touch device.

Check the snippet (works for mouse, fails with touch).

  1. Mousedown on blue element (red element is created)
  2. Keep mouse down and drag to the right (red element gets resized)

I fail making it work for a touch device. I create the element on touchstart, but I am not able to resize it without lifting my finger.

I basically want to achieve the same with touch as with the mouse. Problem is I don't know how the event must look like which I have to trigger on the resize-handle.

I check if it is a touch event and try to change the event.target but this does not work.

if (event.type === "touchstart") {
  console.log("here I am stuck")
  event.target = handler[0];
  item.trigger(event);    
}

$(function(){
  $(document).on("mousedown touchstart", ".resizeCreator", function(event){
    if ($(this).find("div").length){
      return;
    }
    
    //Add resizable div
    $(this).append("<div>resize me</div>");
    $(this).find("div").resizable({handles: "e"});    
    simulateHandleEvent($(this).find("div"), event)
  });
  
  $(document).on("click", "button", function(){
    $(".resizeCreator").find("div").remove();
  });
})

var simulateHandleEvent = function(item, event){
  var handler = item.find(".ui-resizable-e").first();
  
  if (event.type === "touchstart") {
    console.log("here I am stuck")
    event.target = handler[0];
    item.trigger(event);    
  }else{
    handler.trigger("mouseover");
    handler.trigger({
    type: "mousedown",
    which: 1,
    pageX: handler.offset().left,
    pageY: handler.offset().top
  });    
  }
}
.resizeCreator{
  width:200px;
  height:200px;
  padding:5px;
  border:1xp solid black;
  background-color:blue;
}

.resizeCreator div{
  background-color:red;
  display:inline-block;
  padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://raw.githubusercontent.com/furf/jquery-ui-touch-punch/master/jquery.ui.touch-punch.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>

<div class="resizeCreator">

</div>

<button>reset</button>

0

There are 0 best solutions below