Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  107] [ 7]  / answers: 1 / hits: 23996  / 9 Years ago, tue, may 5, 2015, 12:00:00

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.


More From » jquery

 Answers
44

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

[#66732] Monday, May 4, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leighm

Total Points: 423
Total Questions: 101
Total Answers: 112

Location: Turkmenistan
Member since Sat, Apr 16, 2022
2 Years ago
;