JSFiddle - React, Tailwind, and code Playground

by arex1337

HTML

<h1>Goal</h1>
<p>When the user clicks an element (with class="menu"), the default action should not be executed. The user should be presented with a menu with options. When an option has been clicked, then the default action should be executed.</p>
<h1>Problem</h1>
<p>It's very problematic to stop the original click event in the first place, because it seems impossible to restore "default behavior" after that - is there a way to just delay the event until the user clicks a menu item?</p>
<h1>Example 1</h1>
<p>What i want to happen: Click the link. Then click a menu option. The default behavior for the original click is then executed (which means triggering the click event of the originally clicked link and redirection to example.com).</p>
<p><a class="menu" href="http://example.com/">Example link</a></p>
<!--<h1>Example 2</h1>
<p>What i want to happen: Click the tex input. Then click a menu option. The text input is focused.</p>
<p><input class="menu" type="text" value="Example text input" /></p>-->
<div id="placeholder">
    
</div>

CSS

p { margin: 0 0 1em; }
h1,h2,h3,h4,h5,h6 { font-weight: normal; color: #111; }
h1 { font-size: 1.2em; line-height: 1; margin-bottom: 0.5em; font-weight: bold; }

.menu-item, .menu-header {
    display: block;
    color: #fff;
    border: 1px solid #45930B;
    background-color: #4CA20B;
    padding: 0.5em;
}

.menu-header {
    font-size: 1.2em;
    cursor: default;
}

.menu-item {
    cursor: pointer;
}

.menu-item:hover {
    background-color: #4EB305;
}

JavaScript

function createMenu(options) {
    $ul = $('<ul></ul>');
    $ul.append('<li class="menu-header">'+options.header+'</li>');
    for (var $i = 0; $i < options.choices.length; $i++) {
        $ul.append('<li class="menu-item">'+options.choices[$i]+'</li>');
    }
    return $ul;
}

$('.menu').bind('click', function(e) {
    e.preventDefault();
    $('#placeholder ul').remove();
    createMenu({
        header: 'Choose something',
        choices: ['Item 1', 'Item 2', 'Item 3']
    }).appendTo('#placeholder');
});