Im Making a Web Game, and its interface its very simple, composed of:
<div>logo</div>
<div id="map"></div>
<div>some buttons here</div>
Happens that, the div with id = "map" is where my map appears, but also other sections of the game appears too liek the inventory. Im using jQuery to do the ajax stuff, so its like this:
$(document).ready(function() {$('#map').load('map.php');});
The above code load the div for the first time, then when i click a directional button, it calls again that function with some parameters so the player can move, but here's the problem, i'd like to keep the map reloading while im on it.
I Tried to do an:
setInterval("$(document).ready(function() {$('#mapadiv').load('map.php');});",1000);
and in fact it did worked, but when i clicked a button that changed the div and wasnt the map (like the inventory) it rapidly shows the inventory screen and changes again to the map.
Of Course it changes, because the it keeps calling the map! so i thought and tried to put that "setInterval" inside the Map.php so it would only call while its on the screen but that didnt worked too, it did the same as the first try. I think im missing something, can anybody help me? Thanks in advance
I'll asume you have this buttons also:
<input type="button" id="btnInventory" />
<input type="button" id="btnRefreshMap" />
Your script should be like this:
function loadMap(){
$('#map').load('map.php');
$("#map").addClass("keepRefreshingMap"); //This will do the trick
}
function loadInventory(){
$("#map").load("inventory.php"); //Put your loading inventory code here
$("#map").removeClass("keepRefreshingMap"); //Remove the class so it doesn't refresh automatically
}
$(document).ready(function() {
loadMap();
$("#btnRefreshMap").click(function(){ loadMap(); });
$("#btnInventory").click(function(){ loadInventory() });
setInterval(function(){
if($("#map").hasClass("keepRefreshingMap")) //Only refresh if it has the class
loadMap();
}, 1000);
});
As you can see, the trick is in the keepRefreshingMap
class. As long as the map div has it, it will keep refreshing. When you open the inventory, this class is removed, so the map isn't refreshed.
Hope this helps.