Fixing Click Event Issue on Mobile Web UI
As mobile devices are more accessible for browsing and accessing the web, builders of old and new websites and web apps would as much as possible want to make their UI design responsive. But more than aiming for a responsive user interface, it is as well important to have the same satisfactory experience with using larger resolutions. However, one pitfall in adapting a nice user experience on mobile devices is handling — the click event.
Solving in VueJS Framework
I had encountered this issue, thence this article, and I observed that it occurs to elements that one would not expect a click event would happen or when the click event is not attached to an anchor tag. Also, I come to understand that since it’ll be browsed on touch-based interfaces, it would expect to handle another type of event, which is — the tap/touch event and since the issue is happening in a VueJS framework it was easy to utilize a JS package — vue2-touch-events. The fix is just as simple as attaching the tap event to the element as such:
import Vue from 'vue'
import Vue2TouchEvents from 'vue2-touch-events'
Vue.use(Vue2TouchEvents)
and on the html part
<span v-touch:tap="touchHandler">Tap Me</span>
jQuery Specific Issue
If you are having trouble with an old website where jQuery is the prevalent JS library, one fine solution is using .on
function instead of directly using the .click
event.
from
$(document).ready(function() {
$("div.clickable").click(function(){
alert('Clicked');
});
});
to
$(document).ready(function() {
$("div.clickable").on('click', function() {
alert('Clicked');
});
});
You would also be glad to know that jQuery was not left behind on catering touch-based cases. It has the tap
event among other mobile-based events. You can learn more about it at https://api.jquerymobile.com/tap/
Touch Event for Later Browsers
Touch event also becomes available for later browser as soon as mobile devices are being used by the masses. I think this becomes a major support for developers who opted to use native JS.
<div id="tap-able">Tap Here!!</div>
attaching the event goes like this —
function load() {
var el = document.getElementById("tap-able");
el.addEventListener("touchstart", handleStart, false);
el.addEventListener("touchend", handleEnd, false);
el.addEventListener("touchcancel", handleCancel, false);
el.addEventListener("touchmove", handleMove, false);
}
document.addEventListener("DOMContentLoaded", load);// add handle functions ...
See how you can utilized it more at https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
Now, if you have the liberty to change element usage, such as changing div
to an anchor tag, please do so first and see it that works. I think that is a more elegant way of fixing the issue.