简体   繁体   中英

Mobile menu button 2 clicks to toggle the menu

Using: VS 2013, ASP.NET (VB) Webforms.

Upgrading WebForms web site from .NET 2.0 to .NET 4.5 and adding mobile-friendliness for Google support.

Created a button in Top right corner like this:

<a href="#" onclick="toggleMenuDiv();">
    <img class="headerimg-r" src="/images/MenuBtn6464.png" />
</a>

The javascript looks like this:

    function toggleMenuDiv() {
    var menu = document.getElementById('menu');
    if (menu.style.display == 'none') {
        menu.style.display = 'block';
    }
    else {
        menu.style.display = 'none';
    }
}

the element with id "menu" looks like:

<div class="dropdownmenu" id="menu">

However, to drop the menu down I need to touch twice and not once. All menu links work properly without multiple touches.

Feel free to see it yourself. Hit http://www.pedfast.com from a mobile device and give it a try.

I know I'm missing something simple; can someone point me in the correct direction?

Thanks!

Maybe the menu.style.display not equal to none at the beginning?

So, first time youre you click the menu you will set the display to none . And second time the display are none and thats the reason why it works at the second click!

I think you need to check if the display not equal to block then set it to block !

Try this:

if (menu.style.display != 'block') {
    menu.style.display = 'block';
}
else {
    menu.style.display = 'none';
}

EDIT Just look at @Billy Purvis answer. You can also add .toggle() instead of .show() if you want to hide the menu again.

The problem is that the div with the attribute id === "menu" have not the value display: none; as style attribute, so basically at the first click your code is assigning to the element that value, and then, in the second click the value display: block

Extracted from the linked page:

<div class="dropdownmenu" id="menu">

It should be

<div class="dropdownmenu" id="menu" style="display: none;">

Here, I created a jsFiddle showing use of jQuery. It's cleaner and easier to understand and only relies on a single click. I couldn't recreate yours without more code, so I create an example to show the logic, it should be easy to use the logic in your example.

$("button").click(function(){
    $(".menu").show();
});

Once the button (or a tag) is clicked, it'll show the menu. Putting this css on menu hides it until it's needed

.menu {
    display: none;
}

http://jsfiddle.net/yhf3dfcs/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM