I have a basic jQuery dropdown menu and am testing it on mobile devices, specifically phones.
One issue I’ve encountered is that submenus on the right side sometimes go off the edge of the screen, because the text in one or more of the items is too long. The user can, of course, scroll slightly to the right, but that’s not a great solution. There is a similar question here, but I couldn’t get the proposed answers to work (plus I’m fumbling around since I’m still totally new to JS/jQuery).
The general idea seems to be to get the left position+width of the current submenu (making sure they are shown first, then hide them again or show them and shift them when the user taps the menu) and see if that value is greater than the screen width. If it is, then it should be shifted to the left by the difference. However, my attempts don’t seem to do anything to the elements and the menus keep appearing partially off-screen. Currently, I have this (runs after the body loads):
var menus = $('#navbar').find('.subMenu');
menus.show();
menus.each(function(index) {
var offsetMenu = $(this).offset();
var diff = screen.width - ($(this).outerWidth + offsetMenu.left);
if(diff < 0) {
$(this).offset({top:offsetMenu.top, left:offsetMenu + diff});
}
});
menus.hide();
The jQuery version is 1.7.2 and the HTML structure is as follows (simplified version):
<div id="navbar">
<ul>
<li class="dropdown"><a href="#">Link A</a></li>
<li class="dropdown"><a href="#">Link B</a>
<ul class="subMenu">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</li>
</ul>
</div>
How can I get this to work?
Edit: Here’s the relevant CSS, too.
#navbar ul.subMenu {
position:absolute;
display:none;
background-color:#FFAF1E;
}
#navbar ul.subMenu li {
clear:both;
}
#navbar a {
text-decoration:none;
color:#0C1F6E;
display:block;
padding-right:10px;
padding-left:10px;
}
I finally got the following to work:
The only minor caveat is that if you have a menu open as you change the orientation of the phone, the menu may appear off the screen. Closing and reopening the menu will fix this issue. Everything else works perfectly.