I try to create buttons that recolor themselves when clicked. My code for that looks as the follows:
function foo(){
var docFrag = document.createDocumentFragment();
for (var i = 0; i < 4; i++) {
var btn = document.createElement("button");
btn.innerText = i;
btn.id = "testbutton" + i;
(function(btnID){
btn.addEventListener("mousedown", function() {
document.getElementById(btnID).style.backgroundColor = "red";
})})(btn.id);
(function(){
btn.addEventListener("mouseup", function() {
doSomethingElse();
})})();
docFrag.appendChild(btn);
}
document.getElementById("buttonContainer").appendChild(docFrag);
}
It does work in my browser, but when I deploy my code to an emulator it simply skips the coloring part or doesn't do it at all. The reason I use "mousedown" is that I want the buttons to make something else on "mouseup". I previously tried doing both the recoloring as well as the other function on "clicked" but it would then skip the recoloring entirely, since the new function would overwrite the previous work.