Search code examples
javascriptdrop-down-menuonclickfocusonmousedown

Show drop down menu onmousedown without loosing onclick functionality


I try to get a drop down menu to work as most drop down menus seem to work, i.e. as soon as the mouse button is pressed on the trigger the drop menu shows up. Seems rather easy with some css and javascript but it turns out to be a bit tricky.

The obvious way would be this:

<script>
    function toggle(id) {
        var el = document.getElementById(id);
        el.style.display = (el.style.display === 'none') ? 'inline-block' : 'none';
    }
</script>
<input type="button" value="click me" onmousedown="toggle('menu');"><div id="menu" style="display: none">Menu</div>

Unfortunately this is not exactly it, since now it is no more possible to navigate to the trigger with the tab-key and hit enter to show the menu. Seems that this needs the menu to show with onclick. But adding the toggle function to onclick as well shows the menu at onmousedown and then collapses it when the mouse button is released at onclick. Is there a way to stop onclick from firing when onmousedown was firing before?


Solution

  • Hope this would work fine for your requirement

    <script>
        var lastEvent = '';
        function toggle(id, event) {
            event = event || window.event;
            if (lastEvent === 'mousedown' && event.type === 'click' && event.detail > 0){
                lastEvent = event.type;
                return;
            }
        
            var el = document.getElementById(id);
            el.style.display = (el.style.display === 'none') ? 'inline-block' : 'none';
            lastEvent = event.type;
        }
    </script>
    <input type="submit" value="click me" onmousedown="toggle('menu', event);" onclick="toggle('menu', event);">
    <div id="menu" style="display: none">Menu</div>

    https://jsfiddle.net/safeer/rzg7sahb/18/