JSFiddle - React, Tailwind, and code Playground
by bensontrent
HTML
<button id="unique-id" class="btn">JS Hover for Mobile devices<span id="clicked-alert"> Clicked</span>
</button>
<button class="cssonly">CSS Only Button</button>
<br>This js method prevents hover from sticking on an ipad, and prevents the click registering as two clicks. In CSS, if you have any :hover in your css, change them to .hover For example .some-class:hover to .some-class.hover
CSS
button {
display: block;
margin: 20px;
padding:10px;
-webkit-appearance: none;
touch-action: manipulation;
}
.hover {
background: yellow;
}
.btn:active {
background: red;
}
.cssonly:hover {
background: yellow;
}
.cssonly:active {
background: red;
}
#clicked-alert {
display:none;
}
JavaScript
function clicker(id, doStuff) {
id.on('touchstart', function (e) {
id.addClass('hover');
}).on('touchmove', function (e) {
id.removeClass('hover');
}).mouseenter(function (e) {
id.addClass('hover');
}).mouseleave(function (e) {
id.removeClass('hover');
}).click(function (e) {
id.removeClass('hover');
//It's clicked. Do Something
doStuff(id);
});
}
function doStuff(id) {
//Do Stuff
$('#clicked-alert').fadeIn(function () {
$(this).fadeOut();
});
}
clicker($('#unique-id'), doStuff);