Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery onclick not working on mobile

I'm trying to activate a menu with jQuery with a click (touch) on mobile, but it is not working in mobile. When I do the 'window' resize to try the mobile look, it works with the click, but in an emulator or even trying it with my phone, it doesn't work.

HTML Markup

<img src="i/mobilemenu.jpg" id="mobileMenuButton" style="position:absolute; right:0;"/>

CSS:

#mobileNavigation {display:none}

Javascript Code:

<script type="text/javascript">
            $(document).ready(function(){
                    $('#mobileMenuButton').on('click touchstart',function(){

                            if ($('#mobileNavigation').css('display') == 'none') {
                                $('#mobileNavigation').css('display','block');
                            } 
                            else 
                            {
                                    $('#mobileNavigation').css('display','none'); }
                            });
                    });
                </script>
like image 461
vulcanR Avatar asked Sep 29 '22 20:09

vulcanR


2 Answers

Establish a click handler based on the client as such:

var clickHandler = ("ontouchstart" in window ? "touchend" : "click")

and use it whenever you want to listen to click events:

$(".selector").on(clickHandler, function() {...})

This way you can always make sure the proper event is being listened to.

like image 109
elad.chen Avatar answered Oct 03 '22 00:10

elad.chen


<script type="text/javascript">
   $(document).ready(function(){
      $('#mobileMenuButton').on('mousedown touchstart',function(){
            var userAgent = window.navigator.userAgent;
            if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i)||  userAgent.match(/Android/i)) {
         if ($('#mobileNavigation').css('display') == 'none') {
            $('#mobileNavigation').css('display','block');
         } else {
            $('#mobileNavigation').css('display','none'); 
         }
       }
      });
   });
</script>

Just provide the user agent.

like image 38
optimus Avatar answered Oct 03 '22 02:10

optimus