My previous script here worked in hiding and displaying certain divs when called but i want the cookie to remember which one was to be shown so users dont have to continually click the link on every page but so far i have failed in getting the jquery.cookie plug to work with my coding, any help would be great.
working single page:
old code jquery:
function language(chosenlanguage) {
$('div[name|="lang"]').each(function(index) {
if ($(this).attr("class") == chosenlanguage) {
$(this).show(0);
}
else {
$(this).hide(0);
}
});
}
old code html (abreviated with only a href and div):
<div class="language">
<a href="javascript:language('english');">english</a>
<a href="javascript:language('spanish');">spanish</a>
<a href="javascript:language('german');">german</a>
</div>
<div name="lang" class="english" style="display:block;">content</div>
<div name="lang" class="spanish" style="display:none;">content</div>
<div name="lang" class="german" style="display:none;">content</div>
My new code using the jquery.cookie.js plugin is as shown but it does absolutely nothing.
jquery with cookie script:
$(document).ready(function() {
if($.cookie("language")) {
$('div[name|="lang"]').each(function(index) {
if ($(this).attr("class") == $.cookie("language")) {
$(this).show(0);
}
else {
$(this).hide(0);
}
});
}
$(".language a").click(function() {
$('div[name|="lang"]').each(function(index) {
if ($(this).attr("class") == $(".language a").attr("name")) {
$(this).show(0);
}
else {
$(this).hide(0);
}
});
$.cookie("language",$('.language a').attr('name'), {expires: 365, path: '/'});
return false;
});
});
html(abreviated):
<div class="language">
<a href="javascript:language('english');" name="english">english</a>
<a href="javascript:language('spanish');" name="spanish">spanish</a>
<a href="javascript:language('german');" name="german">german</a>
</div>
<div name="lang" class="english" style="display:block;">content</div>
<div name="lang" class="spanish" style="display:none;">content</div>
<div name="lang" class="german" style="display:none;">content</div>
So i’m just wondering what i’m doing wrong?
always sets the value of the cookie to
englishsince that always returns thenameof the first<a />in.languagesalso, you shouldn’t compare classes to strings this way:
.attr('class') == lang, you should instead usehasClass, eg:.hasClass(lang)should look like:
notice i am saving the clicked item in a variable before looping through the divs, you need to do that to have a reference to the clicked item