Search code examples
javascripthtmlcsssettimeoutonblur

Using onblur and setTimeout to close a sub menu


I want to use onblur to close a sub-menu. I've got it to "hide" the sub-menu, but it does just that. I want the menu to go back to its original state. I would also like to set a timeout on the menu so it will close after 5-10 seconds.

P.S I tried to make a jsfiddle for this, and it didnt function. Also, this is for a mobile site.

HTML

<div class="smenu_div"">
    <ul>
      <li>
        <a class="menu-title" href="#" onblur="hidemenu()" onclick="showsub()">Menu</a>
        <ul id='hiddenMenu'>
           <li><a href="/mobile/m.index.html">Home</a></li>
           <li><a href="m.trucks.html">Trucks</a></li>
           <li><a href="m.equipment.hmtl">Equipment</a></li>
         </ul>
        </li>
    </ul>   
</div>

CSS

.smenu_div ul
{

    padding:0px;
    margin-top:5px; 
    margin-right:40px;
    font-family:georgia;
    font-size:70px;
    color:#ffffff;
    list-style:none;
    text-indent:15px;
    text-align:center; 
    width:40%;
    overflow:hidden;
    position: relative;
    display: block;
    float:right;
}

.smenu_div ul li
{

    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    background: rgba(0,0,0,0);
    line-height:justified;
    margin-top: 10px;
    position:relative;
}


/* Changed this so that your hidden menu is hidden by default */
.smenu_div li ul
{ 

  z-index: 50;
  display: none;
  position: relative;
  width: 100%;
  background: transparent;
  float:none;
  }

.smenu_div ul li a
{
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    text-decoration:none;
    color:#ffffff;
    background: #000000;
    display:block;
    position:relative;
}

/* @new */
.smenu_div ul li a.menu-title
{
    padding-right: 50px;
    background: #000000 url('plus.png') no-repeat right center;
    background-size: 75px 75px;

}


.menu-open .smenu_div ul li a.menu-title
{

   background-image: url('minus.png')
}

JavaScript

 var hidden = true;

    function showsub() {

        document.getElementById('hiddenMenu').style.display = (hidden) ? 'block' : 'none';
        document.body.classList.toggle('menu-open');
        hidden = !hidden;


    };

    function hidemenu() {
        document.getElementById('hiddenMenu').style.display =  'none';
        document.body.classList.toggle('plus');
        hidden = !hidden;
    };

Solution

  • there's a mistake in your html code <div class ="smenu_div""> has one too many quotes, so it breaks jsfiddle.

    You almost have it, literally all you're missing in code is

     setTimeout(hidemenu,10000);
    

    from showsub. Note, if you want to prevent it from closing after 10s, if the user keeps pressing on stuff, you'll need some extra code, but if you're ok with it closing 10s after the user clicks on menu no matter what then it's ok.

    here's the fiddle