Anchoring a menu right aligned under a button

A frequent task seems to be positioning a menu element underneath a button (or textbox) so that it appears on top of other elements on the page, and but is aligned to the right hand side of the said button or text box. Here’s one way to do it with Javascript and the prototype library:

 
function pegUnderElement(element, menu) {
     // make menu always on top
     menu.parentNode.removeChild(menu);
     document.body.appendChild(menu);
     menu.style.position = 'absolute';

     // position menu under element
     var pos = element.viewportOffset();
     var w = document.viewport.getWidth();
     menu.style.right = (w - pos[0] - element.offsetWidth) + "px";
     menu.style.top = (pos[1] + element.offsetHeight) + "px";
};

// peg it when window loads
Event.observe(window, 'load', function() {
  pegUnderElement($('button'), $('menu_div'));
});