1

I've been making some basic mobile navigation and am using a click event to show/hide the menu.

A reduced code sample:

        jQuery('.menu-button').click(function(){
            jQuery('.header-nav').toggle();
            console.log('clicked');
        });

I've been remotely debugging on mobile and the console.log always works, but the .header-nav toggle() seems to randomly not trigger - I can't spot a pattern to it, but it always remains in the DOM (which it should), so it being somehow removed is not the reason why it is not firing.

Any ideas?

user319940
  • 3,267
  • 8
  • 38
  • 53
  • 2
    Remains in the DOM how exactly, `toggle` doesn't remove anything, it just hides it ? – adeneo Jan 08 '16 at 16:18
  • Sorry - I mean it's staying in the DOM (which it should), so it being somehow removed is not the reason why it is not firing. – user319940 Jan 08 '16 at 16:20
  • Use ontouch event rather than click event. http://stackoverflow.com/questions/9122679/difference-between-ontouch-and-onclick-android – amitguptageek Jan 08 '16 at 16:24
  • Most likely the click event is sometimes being triggered twice, or something else is toggling the element. – Kevin B Jan 08 '16 at 16:25
  • Kevin B - that does seem to be the case actually - counting the console.log's - any idea why that happens? – user319940 Jan 08 '16 at 16:26
  • are you facing this issue only in mobile devices or in desktop browsers as well? – Mohsin Raza Jan 08 '16 at 16:44

1 Answers1

1

Thanks to Kevin B's comment it seems that the click event is firing multiple times. To fix this, the following was used:

$(element).off().on('click', function() {
    // function body
});

Reference: jQuery click events firing multiple times

Community
  • 1
  • 1
user319940
  • 3,267
  • 8
  • 38
  • 53
  • or... you could move the click event from inside whatever event handler it is in to somewhere else. clearly you don't need to re-bind it. – Kevin B Jan 08 '16 at 16:31
  • I don't think this is necessarily I good solution. Ideally you would find the root cause of "extra" clicks. Good luck! :) – tpdietz Jan 08 '16 at 16:38
  • It's one of those 'works for now' fixes - going to try and investigate further. It's strange though as it's quite a simply function that is called in document.ready and window.resize. – user319940 Jan 08 '16 at 16:45
  • You need to handle 300ms delay when onclick is fired on mobile devices (mostly happen in android smartphones). – Mohsin Raza Jan 08 '16 at 16:46
  • I think that could be the culprit as the same problem doesn't exist on mobile. Fastclick.js seems to be the easiest way to solve this but it seems like a lot of code to remove this Android 'feature'. – user319940 Jan 08 '16 at 16:47
  • you can tackle it by detecting user agent easily for android. – Mohsin Raza Jan 08 '16 at 16:50