Keels
Keels

Reputation: 1

JavaScript mousedown only works on second click

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?

Button id's are 1 through 10 (button1, button2...)

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];
}

I've also tried creating a function that handles mousedown and mouseup. It has the same result.

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];
  };
};

Here's the fiddle: https://jsfiddle.net/Lj8kyr7e/

Upvotes: 0

Views: 1224

Answers (1)

coolnalu
coolnalu

Reputation: 355

mouseup and mousedown events are registered inside click event handler. So the first time the button is clicked, the two events aren't setup yet.

You need to add those events outside of the click handling function. E.g. https://jsfiddle.net/Lj8kyr7e/6/

Upvotes: 2

Related Questions