I created a map where a user can walk from one building to another. Next to the map there’s a small minimap. The “big” map just refreshes by using the load() command. I have got the following code:
$(document).keydown(function(event) {
switch (event.keyCode) {
// A
case 65: $("#world").load("../modules/Map.php?go&move=w"); break;
// W
case 87: $("#world").load("../modules/Map.php?go&move=n"); break;
// D
case 68: $("#world").load("../modules/Map.php?go&move=e"); break;
// S
case 83: $("#world").load("../modules/Map.php?go&move=s"); break;
}
});
Now, right after pressing one of the keys, I want the following to be executed:
$("#minimap").load("../modules/Minimap.php");
I hope you can help me.
You have two choices, but first, let’s refactor slightly (I’ll refactor more in a moment, but let’s start with this):
Now the first load is centralized and we’re not repeating ourselves.
Okay, you have two choices:
Put it after the
switchstatement if you want bothloads to happen at the same time. E.g., picking up at the end:I’ve assumed there that we only want to do it if a key matched. If I’m wrong, move it out of the
if.Use the
successcallback on the firstloadif you want the second load to wait until the first one is complete.More in the docs.
Here’s the more thoroughly refactored version: Have this:
And then either this (option 1 above):
Or this (option 2 above):
Those use an object to map keycodes to directions, taking advantage of the fact you can look up object properties using bracketed notation.
(Don’t worry that
keyCodeis a number but the keys in our map are strings; whenever you use bracketed notation, whatever you give is converted to a string by the JavaScript interpreter. In fact, that’s the case even when you index into an array, since JavaScript arrays aren’t really arrays. But again, we’re using a plain object, not an array.)