Reputation: 8605
I have an index site which checks if a cookie exists and if it has the value EN
. If so it should redirect to an English index.shtml
. Otherwise or if there is no (English) cookie, it should redirect to the German next page:
if (document.cookie) {
var cookieValue = document.cookie;
if (cookieValue.indexOf("MYCOOKIE=EN") > -1) {
window.location.href="en/index.shtml";
}
}
window.location.href="kategorien/hauptkategorie.shtml";
Now something very strange happens: The English cookie exists (I checked cookieValue
with JavaScript alert and it shows EN
), but even though the href inside the if
won't be executed but the 2nd href will be executed. Why is this so?
When I add 2 else
s, it works like expected:
if (document.cookie) {
var cookieValue = document.cookie;
if (cookieValue.indexOf("MYCOOKIE=EN") > -1) {
window.location.href="en/index.shtml";
}
else {
window.location.href="kategorien/hauptkategorie.shtml";
}
}
else {
window.location.href="kategorien/hauptkategorie.shtml";
}
Why is this so that it redirects to hauptkategorie.shtml
if I leave the else
s?
Upvotes: 0
Views: 1678
Reputation: 63709
Probably both window.location.href
statements execute, giving you unexpected results. Try something like:
<script type="text/javascript">
if (document.cookie && document.cookie.indexOf("MYCOOKIE=EN") > -1) {
window.location.href="en/index.shtml";
}
else {
window.location.href="kategorien/hauptkategorie.shtml";
}
</script>
Upvotes: 3
Reputation: 887275
You have a normal Javascript statement after the if
.
There is nothing telling that statement not to run, unless you put it in an else
.
Navigating to a new page does not terminate execution of the current page until the new page actually loads.
Upvotes: 4