14

We are developing a Web-App, which launches on Desktop and on tablets (iPad, Android or a surface). Now we are building our own keyboard for number inputs. When you set the focus on an input field with a mousclick, the costum keyboard opens correct. But when you set the focus to the input with a touched click (tablet), the default keyboard opens also. Our idea is, to detect, if there was a mouse-click or a touched click. If it's a touched click, we can set the readonly="true" property to the input, so the default keyboard on a tabled wouldn't slide in.

Is there a way to detect or check which "type" of click it was (touched or mouse).

webta.st.ic
  • 4,781
  • 6
  • 48
  • 98

2 Answers2

8

You can define an event for the both actions touchend and click then detect which one is triggered using type of the event :

$('#element-id').on('click touchend',function(e){
  if(e.type=='click')
      console.log('Mouse Click');
  else
      console.log('Touch');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="element-id">Click here</button>

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • 3
    Hi Zakaria :) At first thanks for your fast answer. I tried your code. I just changed the id into a class and added the class to two inputs and also changed the console.log print to an alert to see what happened on the tablet. On the desktop it works fine. After I click into the input, the alert "Mouse Click" is on the screen. On the tablet, first the alert "Touch" comes and after I close it, a second alert "Mouse click" also comes to the screen. I think after the touch event it also sends a click event. I tried an e.preventDefault after the alert "Touch". It doesn't help. Have you an idea? – webta.st.ic May 09 '16 at 08:46
1

@Zakaria Acharki

        <script type="text/javascript">
        $(document).ready(function(){
            $(".cCostumeKeyboard").on("click touchstart",function(e){
                if(e.type=="click") {
                    alert("Mouse");
                    alert(e.type);
                }
                else if(e.type=="touchend"){
                    alert("Touch");
                    alert(e.type);
                    e.preventDefault();
                    e.stopPropagation();
                }
            }); 
        });
    </script>

Try this snippet on a touch device. It shows after the first touch on an input follow:

  • Alert: "Touches"
  • Alert: "touchend"
  • Alert: "Mouse"
  • Alert: "click"
webta.st.ic
  • 4,781
  • 6
  • 48
  • 98
  • "touchend" instead of "touchstart" in the onclick :) – webta.st.ic May 09 '16 at 11:22
  • 3
    A touch event also fires a click event. The click event comes after the touchstart or touchend events. So detect the touchend and then preventDefault() before the click event fires. – Marty.H Jun 02 '17 at 18:07