create dynamic map JS
Create a map, move a dot, have fun
by Ford Heacock
HTML
<input type="text" id="color" placeholder="what color map homey">
<div id="wrapper">
<div id="map">
<div id="dot"></div>
</div>
<div id="moves">
</div>
<button id="up" class="btn" data-move="up">up</button>
<button id="down" class="btn" data-move="down">down</button>
<button id="left" class="btn" data-move="left">left</button>
<button id="right" class="btn" data-move="right">right</button>
</div>
<button id="create">create map</button>
CSS
:root {
--top: 0px;
--left:0px;
}
#dot {
position: relative;
left:var(--left);
top:var(--top);
height: 10px;
width: 10px;
background-color: white;
border-radius: 100%;
display: none;
}
JavaScript
//create map of any size
//on button click move dot through map at various increments
var dot = document.querySelector('#dot'),
map = document.querySelector('#map'),
btns = document.querySelectorAll('.btn'),
player = {
x: 0,
y: 0
},
lastMove,
icolor = document.querySelector('#color');
[].forEach.call(btns, function(btn) {
var direction = btn.dataset.move;
btn.onclick = function(){
switch (direction){
case 'up':
$(dot).css("top", "-=10px");
player.x-=10;
break;
case 'down':
$(dot).css("top", "+=10px");
player.x+=10;
break;
case 'left':
$(dot).css("left", "-=10px");
player.y-=10;
break;
case 'right':
$(dot).css("left", "+=10px");
player.y+=10;
break;
}
btn.addEventListener("click", checkMe(player.x, player.y));
};
});
var Map = function(width, height){
this.width = width;
this.height = height;
this.create = function(){
var wrapper = document.querySelector('#wrapper');
var map = document.querySelector('#map');
dot.style.display = 'block';
map.style.backgroundColor = icolor.value;
map.style.height = height + "px";
map.style.width = width + "px";
wrapper.append = map;
}
}
const create = document.querySelector('#create');
create.onclick = function(){
myMap.create();
}
function checkMe(x, y){
if (y < 0 || y >= myMap.width || x < 0 || x >= myMap.height){
alert('oh no baby what is you doin');
player.x = 0, player.y = 0;
$(dot).css("top", "0px"), $(dot).css("left", "0px");
}
}
//lastMove = player.x < 0 ? console.log( 10 ) : console.log( -10 );
var myMap = new Map(500, 300);