Home | History | Annotate | Download | only in js
      1 // Copyright 2013 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 (function() {
      6 
      7 // A simple popup manager.
      8 var activePopup = null;
      9 
     10 function init() {
     11   // Set up the buttons to toggle the popup.
     12   Array.prototype.forEach.call(document.getElementsByTagName('button'),
     13                                function(button) {
     14     var popupId = button.getAttribute('data-menu');
     15     if (popupId == null)
     16       return;
     17     var popup = document.getElementById(popupId);
     18     if (popup == null)
     19       throw new Error('No element with id "' + popupId + '" for popup');
     20     button.addEventListener('click', function(event) {
     21       toggle(popup);
     22       event.stopPropagation();
     23     });
     24   });
     25   // Make clicking anywhere else or pressing escape on the page hide the popup.
     26   document.body.addEventListener('click', function() {
     27     hideActive();
     28   });
     29   document.body.addEventListener('keydown', function(event) {
     30     if (event.keyCode == 27)
     31       hideActive();
     32   });
     33 }
     34 
     35 function toggle(popup) {
     36   if (hideActive() == popup)
     37     return;
     38   popup.style.display = 'block';
     39   activePopup = popup;
     40 }
     41 
     42 function hideActive() {
     43   if (activePopup == null)
     44     return;
     45   activePopup.style.display = ''
     46   var wasActive = activePopup;
     47   activePopup = null;
     48   return wasActive;
     49 }
     50 
     51 init();
     52 
     53 }());
     54