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
     document.body.appendChild(menu); = 'absolute';

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

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