JSFiddle - React, Tailwind, and code Playground
HTML
<button id="open">
Menu should open on hover or touch, and close on click
</button>
<div id="menu" style="display:none;height:100px;width:100px; background-color:grey;">
Menu
</div>
<div style="position:absolute; top:100px;right:0px; height:50px; width:150px;">
Touchscreen? : <span id="hasTouchScreen">false</span>
</div>
JavaScript
var $app = $app || {};
$app = {
hasTouchScreen: false,
handleTouch:function(e){
// fires on the touchstart event
$app.hasTouchScreen = true;
$("#hasTouchScreen").html("true");
$(document).off("touchstart", $app.handleTouch);
},
toggleMenu:function(hide){
// changes the state of the menu
if (hide) {
$("#menu").hide().removeClass("showing");
} else {
$("#menu").show().addClass("showing");
}
},
mouseOver: function(e){
// fires when the mouse over occurs
$app.toggleMenu();
$(document).off("mouseover", "#open", $app.mouseOver);
// detach the mouseover listener
},
mouseOut: function(e){
// fires when the mouseout occurs over the button
$app.toggleMenu(true); // hide the menu
$(document).on("mouseover", "#open", $app.mouseOver);
// reattach the listener
},
click: function(e) {
// fires when a click event occurrs on the button
if ($app.hasTouchScreen) {
e.stopPropagation();
e.preventDefault();
return;
}
//
// since we don't have a touchscreen, close on click.
$app.toggleMenu(true);
},
touch: function(e) {
// fires when a touchstart event occurs on the button
if ($("#menu").hasClass("showing")) {
$app.toggleMenu(true);
} else {
$app.toggleMenu();
}
}
};
$(document).on("mouseover", "#open", $app.mouseOver);
$(document).on("mouseout", "#open", $app.mouseOut);
$(document).on("click", "#open", $app.click);
$(document).on("touchstart", $app.handleTouch);
$(document).on("touchstart", "#open", $app.click);
/*
THE OLD CODE
function openDropDown(){
$('div.dropdown').parent().on('click.open mouseenter', function(event){
$subject = $(this).find('.dropdown-menu')
// console.log(event.type, $subject, "first o");
if(!$subject.is(":visible")){
// console.log($subject, 'second o');
$subject.show()
...