var $ = function (id) { return document.getElementById(id); }; function generatealtartiles() { for (let i = 1; i < 7; i++) { var div = document.createElement('div'); div.id = "at" + i; div.addEventListener("click", function () { buildaltar(i) }); $("altartiles").appendChild(div); } } function buildaltar(tilenumber) { var tileId = "a" + tilenumber; $("altartiles").className = "red"; $(tileId).style.borderColor = "#fff"; }
#altartiles { position: absolute; top: 10px; left: 10px; display: grid; grid-template-columns: 34px 34px 34px; grid-template-rows: 63px 63px; grid-gap: 8px 6px; } #altartiles > div { background-color: #000; border: 2px dashed red; } #altartiles > div:hover { border-color: #fff; } .red > div { border: 2px dashed red; border-color: red; } .red > div:hover { border-color: #fff; }
<body onload="generatealtartiles()"> <div id="altartiles"></div> </body>
EDIT – I added a snippet but it gives an error when I click on one of the divs that I don’t get when running this locally on my machine. When I run it locally the div border does turn white. It just stays white and won’t turn back red unless I specifically turn it back to red by its ID. If I do that though it won’t turn white on hover anymore.
Advertisement
Answer
Have you tried using the :active
decorator instead of adding/removing classes?
.parentDiv > div { border: 2px solid red; } .parentDiv > div:hover, div:active { border-color: white; }
Update after seeing snippet:
var $ = function (id) { return document.getElementById(id); }; function generatealtartiles() { for (let i = 1; i < 7; i++) { var div = document.createElement('div'); div.id = "a" + i; div.onclick = function() { resetTiles(); this.style.borderColor = 'white'; } $("altartiles").appendChild(div); } } function resetTiles(){ for (let i = 1; i < 7; i++) { $("a" + i).style.borderColor = ''; } }
#altartiles { position: absolute; top: 10px; left: 10px; display: grid; grid-template-columns: 34px 34px 34px; grid-template-rows: 63px 63px; grid-gap: 8px 6px; } #altartiles > div { background-color: #000; border: 2px dashed red; } #altartiles > div:hover { border-color: white; }
<body onload="generatealtartiles()"> <div id="altartiles"></div> </body>