How can I make the green square always land on the center of the blue square; it works when I first hit the up key but after that it lands in different positions.
Also, I want to be able to keep the green square from going outside the grid; as you can see, I’m really green when it comes to coding and maybe this takes more complex coding than I realized. But the most common advice has been to try, Google, and ask on forums.
const mun = document.querySelector('.mun')
let xAxis = 0
let yAxis = 0
function control(e) {
switch (e.key) {
case 'ArrowLeft':
xAxis -= 80;
mun.style.left = xAxis + 'px';
break;
case 'ArrowRight':
xAxis += 80;
mun.style.left = xAxis + 'px';
break;
case 'ArrowUp':
yAxis -= 80;
mun.style.top = yAxis + 'px';
console.log(yAxis)
break;
case 'ArrowDown':
yAxis += 80;
mun.style.top = yAxis + 'px';
break;
}
};
document.addEventListener('keydown', control)
.wrapper {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
border: 2px solid black;
}
.one,
.two,
.three,
.four,
.six,
.seven,
.eight,
.nine {
background-color: blue;
border: 1px solid black;
}
#five {
background-color: blue;
border: 1px solid black;
position: relative;
}
.mun {
background-color: green;
width: 35px;
height: 35px;
position: center;
position: absolute;
top: 31%;
left: 32%;
}
<div class="wrapper">
<div class="one">One</div>
<div class="two">Two</div>
<div class="three">Three</div>
<div class="four">Four</div>
<div id="five">Five
<div class="mun"></div>
</div>
<div class="six">Six</div>
<div class="seven">Seven</div>
<div class="eight">Eight</div>
<div class="nine">Nine</div>
</div>
2
Answers
There you go. You should be able to improve this by finding an algorithm that can find the neighboring elements. Here is the jsfiddle as well: https://jsfiddle.net/28dzk1e7/25/
Another approach is to not hardcoding based on rows and columns count. Instead, rows/columns count could be retrieved from css code.
Also, the mun div could be created at page load ant put in the div marked by an attribute (selected="true" in this example).
The grid is not necessarily square or even complete.