Osman Osman - 4 months ago 8
HTML Question

How to select a random div through a button?

I have a menu bar along with three different hidden menus. When the user clicks the "Random button", a random menu is selected and that becomes the default menu.

This means that if the user clicks on the menu bar, the default menu should open up.

If the user hits the "Random button" again, a new random menu will be selected as the default.

The code below is able to select a random menu. However, if the user clicks on the menu bar, all of the hidden menus will be shown at the same time rather than the default menu (selected randomly upon hitting the "Random button").

HTML:

<p class="random">Random</p>

<i class="fa fa-menu"></i> (This is the menu bar)

<nav class="menu_cover" style="display: none">Menu one</nav>
<nav class="menu_cover" style="display: none">Menu two</nav>
<nav class="menu_cover" style="display: none">Menu three</nav>


JavaScript:

$('.random').click(function(e) {
var random_menu_cover = Math.floor(Math.random() * $('.menu_cover').length);

$('.menu_cover').hide().eq(random_menu_cover).show().css("display", "none");
});


The jQuery is a simple hide and show code. As a result of this, clicking the menu bar will "hide" and "show" all of the three menus at the same time.

How would I modify this code so that the menu bar only affects the default menu that was selected by random?

I hope this question makes sense.

Thanks

Answer

Save a reference to the randomly picked menu element, or give the element a class to which select it by

var defaultMenu = null;
$('.random').click(function(e) { 
    var random_menu_cover = Math.floor(Math.random() * $('.menu_cover').length);
    defaultMenu && defaultMenu.hide();
    defaultMenu = $('.menu_cover').eq(random_menu_cover);
});

Then in your menu button just check defaultMenu is set and if so toggle it

$(".somebutton").click(function(){
   defaultMenu && defaultMenu.toggle();
});

Demo

var defaultMenu = null;
$('.random').click(function(e) {
  var random_menu_cover = Math.floor(Math.random() * $('.menu_cover').length);
  //Hide the old one, if one
  defaultMenu && defaultMenu.hide();
  defaultMenu = $('.menu_cover').eq(random_menu_cover);
});

$(".fa-menu").click(function() {
  defaultMenu && defaultMenu.toggle();
});
.menu_cover {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="random">Random</p>

<i class="fa fa-menu">Show/hide menu</i> (This is the menu bar)

<nav class="menu_cover">Menu one</nav>
<nav class="menu_cover">Menu two</nav>
<nav class="menu_cover">Menu three</nav>