Reputation: 304
$(document).ready(function() {
var hrefs = {
"en": ["includes/test1.html", "includes/test2.html"],
"es": ["includes/test3.html", "includes/test4.html"]
}
$(function() {
var cookie = Cookies.get('langCookie');
if (cookie) {
$("#div1").load(hrefs[cookie][0]);
$("#div2").load(hrefs[cookie][1]);
}
$("[hreflang]").on("click", function() {
var lang = $(this).attr("hreflang");
Cookies.set('langCookie', lang);
$("#div1").load(hrefs[lang][0]);
$("#div2").load(hrefs[lang][1]);
});
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="js-cookie/src/js.cookie.js"></script>
<a href="#" hreflang="en" onclick="window.lang.change('en'); return false;">English</a> | <a href="#" hreflang="es" onclick="window.lang.change('es'); return false;">Spanish</a>
Having issues with loading content based on Cookie value.
My div is set up this way:
<div id="prs"> </div>
I have a pseudo language switcher, that if based on cookie, should load an html file into the div:
$(document).ready(function() {
var cookie = Cookies.get('langCookie');
if((cookie) === 'en')
{
$("#prs").empty();
$("#prs").load("includes/test.html");
}
else if((cookie) === 'th'){
$("#prs").empty();
$("#prs").load("includes/test2.html");
}
else if((cookie) === 'es'){
$("#prs").empty();
$("#prs").load("includes/test3.html");
}
However, when I click on the link to switch Language, the cookie is set however I have to reload the page to see the new content. As you can see in my script above, I tried to initiate an "empty()" on the div before the loading of the content. this of course doesn't work. I've read that the issue could be related to the $(document).ready(fucntion)
How can I call it so that the div is reloaded with the content, once the cookie is set to the new language, and the div is updated with the correct loaded html file?
edit to add:
HTML for Language switching (link based):
<div id="langChanger"><a href="#" onclick="window.lang.change('en'); return false;">Switch to English</a> | <a href="#" onclick="window.lang.change('th'); return false;">Switch to Thai</a> | <a href="#" onclick="window.lang.change('es'); return false;">Switch to Spanish</a></div>
Update: included snippet below per request. Using js-cookie.js to create cookie.
Upvotes: 0
Views: 1367
Reputation: 177851
This will work better.
Note the unobtrusive event handling and usage of the actual variable instead of testing it every time
var hrefs = {
"en": "includes/test.html",
"th": "includes/test2.html",
"es": "includes/test3.html"
}
$(function() {
var cookie = Cookies.get('langCookie');
if (cookie) {
$("#prs").load(hrefs[cookie]);
}
$("[hreflang]").on("click", function() {
var lang = $(this).attr("hreflang");
Cookies.set('langCookie', lang);
$("#prs").load(hrefs[lang]);
});
})
<div id="langChanger">
<a href="#" hreflang="en">Switch to English</a> |
<a href="#" hreflang="th">Switch to Thai</a> |
<a href="#" hreflang="es">Switch to Spanish</a>
</div>
Upvotes: 2