Home > Enterprise >  Trigger touch event onclick
Trigger touch event onclick

Time:12-12

I have an element which works only ontouch(start), and I want to make that onclick will trigger ontouch (for non-touchable devices, such as my pc). like:

element.onclick = element.touchStart();

or:

element.onclick = element.touch();

Is something like this possible?

CodePudding user response:

You need to create a new touch event using new Event, and dispatch it to the element, using dispatchEvent method of event.target.

let div = document.querySelector("div");

div.addEventListener("click", (e)=>{
  var event = new Event('touch');
  e.target.dispatchEvent(event)
});

div.addEventListener("touch", (e)=>{
  console.log("touched");
});
#test{
  background: red;
  width: 200px;
  height: 200px;
}
<div id="test"><div>

  • Related