title: JavaScript mousedown only works on second click
body: <p>I want the buttons to change their color when they're clicked (a darker shade on mousedown and their original color on mouseup) and it works but only on the second click. Why is that? And how can I fix this?</p>
  
  <p>Button id's are 1 through 10 (button1, button2...)</p>
  
  <pre><code>document.getElementById('main').addEventListener('click', function(e) {
  
  var buttonNum = e.target.id.substring(6);
  
  if (e.target.id.substring(0,6) === "button") {
    e.target.addEventListener('mousedown', function() {mouseDown(buttonNum)}, false);
    e.target.addEventListener('mouseup', function() {mouseUp(buttonNum)}, false);
    // trying another way:
    // mouseEventHandler(buttonNum);
    result.innerHTML = e.target.innerHTML + " was clicked";
  }
  
  }, false);
  
  var mouseupColors = ["#CE3737",
                                    "#48935C",
                                    "#FFD454",
                                    "#26567C",
                                    "#FF6528",
                                    "#92898A",
                                    "#AF9FA5",
                                    "#9EA9AA",
                                    "#989788",
                                    "#7C7372"]
  
  var mousedownColors = ["#B52D2D",
                                         "#397A4A",
                                         "#E5BF4B",
                                         "#183F63",
                                         "#E55B24",
                                         "#777071",
                                         "#96888D",
                                         "#879091",
                                         "#7F7E71",
                                         "#635C5B"]
  
  function mouseDown(buttonNum) {
    var buttonId = "button" + buttonNum;
    document.getElementById(buttonId).style.backgroundColor =         mousedownColors[buttonNum - 1];
  }
  
  function mouseUp(buttonNum) {
    var buttonId = "button" + buttonNum;
    document.getElementById(buttonId).style.backgroundColor =   mouseupColors[buttonNum - 1];
  }
  </code></pre>
  
  <p>I've also tried creating a function that handles mousedown and mouseup. It has the same result. </p>
  
  <pre><code>var mouseEventHandler = function(buttonNum) {
    var buttonId = "button" + buttonNum;
    document.getElementById(buttonId).onmousedown = function() {
    this.style.backgroundColor = mousedownColors[buttonNum - 1];
    };
    document.getElementById(buttonId).onmouseup = function() {
    this.style.backgroundColor = mouseupColors[buttonNum - 1];
    };
  };
  </code></pre>
  
  <p>Here's the fiddle: <a href="https://jsfiddle.net/Lj8kyr7e/" rel="nofollow">https://jsfiddle.net/Lj8kyr7e/</a></p>