So here’s another problem we encountered recently on a client site and had to come up with a solution that worked with their environment. The client needed content displayed dynamically on a page that would be different based on the visitor’s location. Now, we would usually do this in PHP using the MaxMind IP database or something similar, but this client site had page caching and CloudFlare setup, meaning this couldn’t be done server-side. So we had to come up with a solution using only JavaScript.
The client needed different prices displaying on a page depending on location, but this would work with any content. You could have a button in different languages, or create a popup/lightbox that redirects a visitor a different location-specific domain. So on to the tutorial:
The above code will insert the price based on country into any element with the class “update_price”. So the two dynamically displayed prices above are just two divs: <div class="update_price"></div>
Now that’s using vanilla JS with not plugins. Some may prefer to use jQuery…
If you want to use jQuery to insert the values into the elements, make sure jQuery is included above the code. Then remove this part from the above code:
And replace it with this:
$('.update_price').html(display_price);
No we have something basic, we can add some more functionality. Firstly add in a URL parameter to override the country returned from the IP. So for example we want to force the display of Japanese Yen, we’ll do this via the URL parameter “country=” which in this case will equal “JP” (as in Japan). So to force JPY on this page, the URL is: https://www.thewebtaylor.com/articles/how-to-dynamically-display-content-based-on-geo-ip-location-using-only-javascript?country=JP.
For this added functionality, we will need to add a new function to get the URL parameter. Put this at the top of the code:
Then remove this part:
// Get country code based on IP var country_code = json.country_code;
And replace with this:
And that’s it! If you have any issues, feedback or improvement ideas please let us know in the comments…