Last Good Quote: Son's are the seasoning on our lives. - Someone on Facebook

Friday, April 2

Code: Simple 2D Javascript Map - Part 2

So, we've built a map in javascript and displayed it. Quite impressive...or maybe not.

Now we want to make something happen when the user clicks on a tile. In this example, we will change the background. First we add a simple function which we will call whenever a tile is clicked.

function tileClicked(x,y)
{
var tile = document.getElementById("tile_" + x + "_" + y)
tile.style.background = "yellow"
}


Now, we will attach this function to all the tiles, so within our buildMap() function we add this line of code:

d.setAttribute("onclick","tileClicked(" + x + "," + y + ")")


That's it...now when you click a tile, it turns yellow. Why don't you try to change it so that the background has an image and the image changes as you click it?

Full Code:


<html>
<style>
.tile {
background:#BBB;
border:1px solid #999;
position:absolute;
top:0px;left:0px;
width:5px;height:5px;
overflow:hidden
}
</style>
<script language=javascript>

var originX = 0;
var originY = 0;
var tileSize = 32;

function buildMap(width, height)
{
for(x=0;x<width;x++)
for(y=0;y<height;y++)
{
var d = document.createElement("DIV");
d.className="tile";
d.setAttribute("ID","tile_" + x + "_" + y);
d.style.top = originY + (y*tileSize);
d.style.left = originX + (x*tileSize);
d.style.width = tileSize;
d.style.height = tileSize;
d.setAttribute("onclick","tileClicked(" + x + "," + y + ")")
document.getElementById("divMap").appendChild(d);
}
}

function tileClicked(x,y)
{
var tile = document.getElementById("tile_" + x + "_" + y)
tile.style.background = "yellow"
}


</script>
<body onload="buildMap(10,10)">

<div id="divMap"></div>

</body>
</html>

0 comments:

Post a Comment

Followers