Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trigger touch event onclick

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading