JQuery onclick not working on mobile devices

I am trying to activate a menu using jQuery by clicking (tapping) on โ€‹โ€‹a mobile device, but it does not work on mobile devices. When I resize the window to try the mobile view, it works with a click, but in the emulator or even tries to use it with the phone, it does not 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> 
+5
source share
4 answers
 <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 specify the user agent.

0
source

Install a client-based click handler as such:

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

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

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

Thus, you can always make sure that the corresponding event is being listened.

+3
source

I remember when I created the mobile application, elements that were not links could not pick up the click event if I did not give them the CSS cursor: pointer property. Perhaps this is a similar problem. Try specifying this function in the style attribute.

+1
source

I went through this question and realized that click (and touchstart) should work.

@vulcanR, it does not work in your case, because you already have #mobileNavigation as display: none ; Thus, there is no place to trigger an event.

Instead, try the following code and it should work -

 $(document).ready(function() { $('#mobileMenuButton').on('click touchstart', function() { if ($('#mobileNavigation').css('opacity') == '0') { $('#mobileNavigation').css('opacity','1'); } else { $('#mobileNavigation').css('opacity','0'); } }); }); }); 

The reason for this work is that opacity:0 preserves the height and width of the element, while display:none makes the measurements equal to zero, so there is no property for the event. You could also use visibility:hidden , but this does not listen to the click event or any events at all.

0
source

Source: https://habr.com/ru/post/1202696/


All Articles