Fron Melfi
Fron Melfi

Reputation: 3

JavaScript redirection to alternative index

I need to change my index according to language of visitors.

I try this code but it's not working

<script type="type/javascript">

var language = navigator.language || navigator.browserLanguage;

if (language.indexOf('es') {
window.location = '../index.html';
} else {
window.location = '../index2.html';
}
</script>

Upvotes: 0

Views: 60

Answers (2)

Ponmani Chinnaswamy
Ponmani Chinnaswamy

Reputation: 865

This is working ...you missed ")"

<script type="type/javascript">

var language = navigator.language || navigator.browserLanguage;

if (language.indexOf('es')>-1) {
window.location = '../index.html';
} else {
window.location = '../index2.html';
}
</script>

Also you have to use with condition as @Zoli Szabo said.

Upvotes: 2

Zoli Szab&#243;
Zoli Szab&#243;

Reputation: 4534

You may want to consider that language.indexOf('es') will return 0 (== false) for 'es*' language codes, because the index of the first character is 0. If 'es' is not found, the indexOf() method will return -1.

So, if your "index.html" is the spanish version and "index2.html" the international version, your code should look like this:

<script type="type/javascript">
var language = navigator.language || navigator.browserLanguage;

if (-1 < language.indexOf('es')) {
  window.location = '../index.html';
} else {
  window.location = '../index2.html';
}
</script>

Upvotes: 1

Related Questions