0

I am making a geo quiz with a map. I have this function to load different country names randomly.

<h1>Can you locate

<script type="text/javascript">

generateCountry();


function generateCountry(){

filenames = [ "Greece", "France", "Italy", "United Kingdom", "Germany" ];

filename = filenames[Math.floor(Math.random()*filenames.length)];

document.write(filename);
}


</script>
on the map?
</h1>

and I am using google maps, where when I click the right country with a function I'm getting an alert of whether I was right or wrong.

   function getCountry(latLng) {
              geocoder.geocode( {'latLng': latLng},
                function(results, status) {
                  if(status == google.maps.GeocoderStatus.OK) {
                    if(results[0]) {
                      for(var i = 0; i < results[0].address_components.length; i++) {
                        if(results[0].address_components[i].types[0] == "country") {
                          if(results[0].address_components[i].long_name == filename) {
                              alert("right");

                                generateCountry();

                           } else {
                              alert("wrong");

                           }
                        }
                      }
                    }


                    else {
                      alert("No results");
                    }
                  }
                  else {
                    alert("Status: " + status);
                  }
                }
              );
      }  

when the quiz loads I see the first question for example : Can you locate France on the map? and the map responds well. When I click the right one, the map after that seems to recognize a new country in the filename variable as when I click on the other countries I finally get a right on Germany for instance. So the map seems to be getting it right. The problem is that the name on the question above doesn't change from France to Germany. What do I need to do so that after clicking ok on the first question's right alert a new country name is loaded, without reloading the whole page of course? I know I am probably not using the best way to do it so any help and guidance would be appreciated.

niaoy
  • 81
  • 2
  • 9

1 Answers1

0

Don't use document.write. Instead, place an empty span in the text and give it an id, like this:

<h1>Can you locate <span id="country"></span> on the map?</h1>

Then, when you want to change it, get the element using the DOM and change the text:

document.getElementById('country').textContent = "Germany";

Another benefit of doing it this way is that the script doesn't have to be in the middle of the h1; you can move it to the head or the end of the body, depending on which you prefer.

Community
  • 1
  • 1
Tom Smilack
  • 2,007
  • 14
  • 18