Thursday, October 17, 2013

Centering a submenu that is wider than it's parent with js/jQuery

Recently our graphic designers tend to create menus like on the picture below:


While it looks very nice it is not at all easy to recreate outside Photoshop only with html and css. The problem is that the submenu has to be centered for the triangles to align perfectly. This is achieved by setting the submenu's left css property to a calculated negative value.

Unfortunately this is not enough as the content width of each menu element can change depending on the browser that is being used and the client might change the content anyway.

We need to use some javascript to determine the exact value of the negative left value.

The html code is something like this:

 <ul id="menu">  
      <li>Home</li>  
      <li>Policy</li>  
      <li>For companies  
           <ul>  
                <li>Submenu item 1</li>  
                <li>Submenu item 1</li>  
           </ul>  
      </li>  
      <li>About us</li>  
      <li>Contact</li>  
      <li>Login</li>  
 </ul>  

Sorry, no CSS this time, if you want to use this, you can probably write your own :-)

Using this js/jQuery code, the submenu will be properly aligned:

 <script type="text/javascript">  
      $(document).ready(function(){  
           $("ul#menu li").hover(function(){  
                var outerWidth = $(this).width();  
                var innerwidth = $(this).find("ul").width();  
                var difference = (innerwidth - outerWidth) / 2;  
                $(this).find("ul").css("left", -difference);  
           });  
      });  
 </script>