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:

See The Demo

How to display dynamic pricing based on country using JavaScript

These prices are dynamically displayed based on your location:

Simple implementation with vanilla JavaScript:

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…

Simple implementation with 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:


Adding a bit more functionality

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:

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:

So now our whole code should look like this:

See The Demo

And that’s it! If you have any issues, feedback or improvement ideas please let us know in the comments…

Free Graphics, Icons, Tutorials
Free Graphics Free Christmas Vector Icon Graphics Pack 2017Free Fitness Vector Icons Graphics PackFree Camping Vector Graphics PackFree Summer Graphics PackFree File Icon PackFree Fast Food Vector Graphics
Sharing is caring...
Like & Follow
Share the love, share this page! Facebook Twitter Digg Reddit LinkedIn Pinterest Email
Close [X]
The Web Taylor
1000 Lakeside North Harbour Portsmouth, Hampshire PO6 3EN
02392 123358