Summary
This howto demonstrates one method for getting a button to work on both mobile and desktop ( touch and mouse click) without using jQuery. it uses vanilla JavaScript and should work on most platforms.
The Problem
While coding a site I wanted a button to fire an event that hid some items on the page and showed others. I added the normal onClick=’doMyFunction()’ to the button and tested. This code did not fire events on a Samsung browser but worked beautifully on the desktop. Hmmm .. how to solve this?
I looked up Stack Exchange, MSD docs etc but all the solutions involved loading jQuery. Why would i want to add thousands of lines of code for one small button? SO I found a plain JavaScript, No jquery code solution.
The Solution
I added this to the bottom of my code and it is working for both touch and desktop. I have found it helps to fire the event through adding an event listener. There are two listeners added as click (for mouse) and touchend ( for touch) are mutually exclusive on touch and mouse .
Adding an event to an element
let myButton = document.querySelector('.button-class');
// desktop
myButton.addEventListener('click', function (ev) {
myFunction(myButton.value);
}
// touch
myButton.addEventListener('touchend', function (ev) {
myFunction(myButton.value);
}
);
If adding listeners for your button (one for touch and other desktop ) you could have problems
Many solutions involve adding two listeners, one for mobile / touch and one for desktop / mouse. However there is a chance both listeners could get fired calling your code twice. There are some platforms / events where both the events will fire. There are some solutions to that below.
- Add a static variable in the called function to check if it has already been called
- Add two mutually exclusive events that don’t fire on both touch / desktop e.g touchend event for a button on a mobile and click for a button on a desktop
- Check if the previous state is the same as the current state and if it is cancel going further. For my example that would involve having a variable that keeps the last myButton.value acted on.