Search code examples
javascriptjquerycssjquery-mobiletouch

Jquery click event not working on mobile device


I am trying to make the below JSFiddle work for tablet/mobile devices (e.g. 'on touch' as well as 'click').

https://jsfiddle.net/lkw274/7zt1zL0g/87/


<div class="user-navigation">
        <a class="mobile-menu-new" href=""><span></span>Menu</a>
</div>

$(document).ready(function() {
$(".user-navigation a.mobile-menu-new").click(function (e) {
      e.preventDefault();
    $(".user-navigation a.mobile-menu-new").toggleClass("current");
    }); 
});

.current { background: #F00;}

Expected behaviour: On clicking 'Menu', either by touch or with clicked with mouse, the background is highlighted red until it is clicked again when the class should be removed, removing the red background and returning it to its original state.

Current behaviour: On clicking 'Menu', by touch on mobile/tablet device, the background is highlighted red however the class is not removed when 'menu' is clicked for the second time.

Could anyone help to understand how this code needs to be modified for tablet/mobile devices?

I have tried the solution in the below StackOverflow link however this did not function on click once implemented.

document-click-function-for-touch-device

Thanks in advance.


Solution

  • Looks like event delegation is the way to do this since, when you modify the target element, bind seems to fail.

    Try the following (works on my iPhone/Chrome).

    $(document).ready(function() {
        $(".user-navigation").delegate("a.mobile-menu-new", "click", function (e) {
            e.preventDefault();
            $(this).toggleClass("current");
        });
    });
    

    Please note I have used .delegate since you seem to be using jQuery 1.6 (as per your fiddle) as otherwise, with jQuery 1.7+, you could use .on like below.

    $(document).ready(function() {
        $(".user-navigation").on("click", "a.mobile-menu-new", function (e) {
            e.preventDefault();
            $(this).toggleClass("current");
        });
    });