I have function that works on click
$('#test').click(function(e){
// some code
});
How can I check if the test
element clicked or touched?
I have function that works on click
$('#test').click(function(e){
// some code
});
How can I check if the test
element clicked or touched?
You could use one event for the both then detect type of the event triggered :
$('#test').on('touchend click',function(e){
if(e.type=='click')
alert('click triggered');
else
alert('touch triggered');
});
Hope this helps.
$('#test').on('touchend click',function(e){
if(e.type=='click')
alert('click triggered');
else
alert('touch triggered');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">TEST</button>
Since I needed a vanilla JS solution and this was the first result that popped up in Google, I thought more people could find my discovery useful, so I'm writing this answer.
I've found this code in a Medium comment (who would have thought) while looking for the solution to this very problem, so I wrapped in a function and works like a charm for me:
function isTouchScreen() {
return window.matchMedia('(hover: none)').matches;
}
You might want to checkout the browser compatibility before implementing in your site, but it was fine for me.
As pointed out by @udoG, the solution is to use the pointerType
.
if you are using jQuery
:
$(selector).click(e => {
if (e.pointerType === "mouse") {} // mouse event
else {} // touch event
});
if you are using vanilla JS
:
element.addEventListener('click', e => {
if (e.pointerType === "mouse") {} // mouse event
else {} // touch event
});
If you are using React
, the event is wrapped around a synthetic event. To access the pointerType
, you have to use the nativeEvent
of the react event. Here is what you need to consider (especially if you are using Typescript). If the event is triggered by a mouse, the native event is an instance of MouseEvent
which does not have pointerType
, so, first you need to check the type of native event which will also take care of the typing problems in TS
<div
onClick={e => {
if (e.nativeEvent instanceof PointerEvent && e.nativeEvent.pointerType === 'touch') {} // Touch Event
else {} // Mouse Event
}}
></div>
Pro tip: If you want to test the touch event in development, use Chrome following this. Note that Safari has a responsive mode which simulates the framework of iPhones and iPads. However, Safari always registers a mouse event even when you are in responsive design mode and have selected an iPhone or iPad.
Solution for modern browsers:
$('#test').click(function(e){
if (e.pointerType === "mouse") {
// clicked with mouse
} else {
// probably touch
}
});
The solution itself is based on vanilla JavaScript, but should work with jQuery as well, as coded here.