I have a slide in menu using vanilla javascript for use on phones, but so far all my tests have resulted in the mobile browsers ignoring the first tap (have tried both touchstart & click as events). Starting with the second tap it works beautifully with each and every subsequent tap.
As opening & closing the menu is the only javascript function on the pages, I don't want to load a huge library, I want to keep it simple and small. My code is below:
var b = document.getElementById('menubtn');
b.addEventListener('touchstart', function (e) {
var n = document.getElementById('nav');
var ns = n.style.left;
if (ns == "-600px") {
n.style.left = "0px";
} else {
n.style.left = "-600px";
}
e.preventDefault();
});
Any ways to easily eliminate this need for double clicking the first time?
In the fwiw dept, it is a responsive design, with the nav menu in a column on big screens and a slide in on phones.
Edit: Solved the issue
Following through on Matt Styles comment, I tried using classList.toggle
and it solved the issue. The final version is below:
var b = document.getElementById('menubtn');
var n = document.getElementById('nav');
b.addEventListener('touchstart', function () {
n.classList.toggle('shwmenu');
setTimeout(function () {
b.classList.toggle('shwmenu');
}, 500);
});
I added the delayed menubtn code to toggle the icon between closed and open states.
The behaviour you describe could be caused by the following:
In your JS you try to implement some kind of On-Off toggle for your nav element, differentiated on the left
CSS property value, with -600
representing the off
value and 0
representing the on
value.
As you said, toggling between those states seems to work fine, but what happens when your element is NOT initialized on exactly -600
? Then on your first tap you will always run into your else clause and set it to -600
first, showing effectively no visual effect on your first tap, just as you describe.
For an instant test, just swap the if-else clause around to turn it on
when style.left is not -600
and then maybe work up towards a more dynamic differentiation between your states ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With