lkw3274
lkw3274

Reputation: 33

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.

Upvotes: 3

Views: 24084

Answers (4)

Hugh
Hugh

Reputation: 45

Well, in modern jQuery versions, I suppose something like this:

    $(document).on('click','selector', function(e){
        e.preventDefault();
        your code here
    });

...would do the trick for mobile devices...

Upvotes: 0

Arian Al Lami
Arian Al Lami

Reputation: 937

add the cursor:pointer to the property of your class and it should work find in mobile

.user-navigation{ cursor:pointer }

Upvotes: 3

gem007bd
gem007bd

Reputation: 1165

$(selector).bind("click touchstart", function(){
       .......
});

Upvotes: 1

lshettyl
lshettyl

Reputation: 8171

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");
    });
});

Upvotes: 3

Related Questions