JAVASCRIPT   161

script.js

Guest on 20th July 2021 03:55:22 PM

  1. // add event handler realization
  2. var addEvent = (function () {
  3.   if (document.addEventListener) {
  4.     return function (el, type, fn) {
  5.       if (el && el.nodeName || el === window) {
  6.         el.addEventListener(type, fn, false);
  7.       } else if (el && el.length) {
  8.         for (var i = 0; i < el.length; i++) {
  9.           addEvent(el[i], type, fn);
  10.         }
  11.       }
  12.     };
  13.   } else {
  14.     return function (el, type, fn) {
  15.       if (el && el.nodeName || el === window) {
  16.         el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
  17.       } else if (el && el.length) {
  18.         for (var i = 0; i < el.length; i++) {
  19.           addEvent(el[i], type, fn);
  20.         }
  21.       }
  22.     };
  23.   }
  24. })();
  25.  
  26. // variables
  27. var aLoops = []; // sound loops
  28.  
  29. // initialization
  30. addEvent(window, 'load', function (event) {
  31.  
  32.     // load music files
  33.     aLoops[0] = new Audio('media/background.ogg');
  34.     aLoops[0].volume = 0.3;
  35.     aLoops[1] = new Audio('media/button.ogg');
  36.     aLoops[1].volume = 1.0;
  37.     aLoops[2] = new Audio('media/button_click.ogg');
  38.     aLoops[2].volume = 1.0;
  39.  
  40.     aLoops[0].addEventListener('ended', function() { // loop background sound
  41.         this.currentTime = 0;
  42.         this.play();
  43.     }, false);
  44.     aLoops[0].play();
  45. });
  46.  
  47. // all the buttons
  48. var aBtns = document.querySelectorAll('#nav li');
  49.  
  50. // onmouseover event handler
  51. addEvent(aBtns, 'mouseover', function (event) {
  52.     aLoops[1].currentTime = 0;
  53.     aLoops[1].play(); // play click sound
  54. });
  55.  
  56. // onmouseout event handler
  57. addEvent(aBtns, 'mouseout', function (event) {
  58.     aLoops[1].currentTime = 0;
  59.     aLoops[1].pause(); // play click sound
  60. });
  61.  
  62. // onclick event handler
  63. addEvent(aBtns, 'click', function (event) {
  64.     aLoops[2].currentTime = 0;
  65.     aLoops[2].play(); // play click sound
  66. });

Raw Paste


Login or Register to edit or fork this paste. It's free.