JSFiddle - React, Tailwind, and code Playground

by Niwo04

HTML

<div class="mouse-device"></div>                  <!-- this will always be a div that changes style on hover -->
<div id="touch_div" class="margin-top"></div>   <!-- this will be identical to the first div when you're not on a touch device, but it will change to touch sensitive when you are on a touch device -->

CSS

.mouse-device {
  width: 100px;
  height: 100px;
  background-color: purple;
}
.mouse-device:hover {
  background-color: green;
}
.touch-device {
  margin-top: 10px;
  width: 100px;
  height: 100px;
  background-color: red;
}
.touch-device-hovered {
  margin-top: 10px;
  width: 100px;
  height: 100px;
  background-color: blue;
}
.margin-top {
  margin-top: 10px;
}

JavaScript

let touch_div = document.getElementById('touch_div');
let is_touch_device = false;
let touchstart_event_listener; 	// save the event listeners, if you want to delete them later
let touchend_event_listener; 		// save the event listeners, if you want to delete them later


if ("ontouchstart" in document.documentElement) {	// check if touch is enabled on device
  is_touch_device = true;
}

if (is_touch_device) {
	touch_div.classList.add('touch-device');	// adds a class to style the div for touch devices
  
  touch_div.addEventListener('touchstart', touchstart_event_listener = () => {	// event listener changes the class to hovered when you put your 
  	touch_div.classList.replace('touch-device', 'touch-device-hovered');				// finger on the div
  });
  
  touch_div.addEventListener('touchend', touchstart_event_listener = () => {		// event listener changes the class back to not hovered when you 
  	touch_div.classList.replace('touch-device-hovered', 'touch-device');				// release your finger
  });
} else {
	touch_div.classList.add('mouse-device');	// adds a class to style the div for mouse devices
}