Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if input was touched (tablet) or clicked (mouse)

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).

like image 691
webta.st.ic Avatar asked May 09 '16 08:05

webta.st.ic


2 Answers

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.

like image 180
Zakaria Acharki Avatar answered Oct 18 '22 09:10

Zakaria Acharki


@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"
like image 36
webta.st.ic Avatar answered Oct 18 '22 08:10

webta.st.ic