I am new to jQuery. This code worked for me to change text in html:
// Some variables for later
var dictionary, set_lang;
// Object literal behaving as multi-dictionary
dictionary = {
"english": {
"_hello": "Hello",
"_january": "January"
},
"portuguese": {
"_hello": "Oie",
"_january": "Janeiro"
},
"russian": {
"_hello": "привет",
"_january": "январь"
}
};
$(function () {
// Lets be professional, shall we?
"use strict";
// Function for swapping dictionaries
set_lang = function (dictionary) {
$("[data-translate]").text(function () {
var key = $(this).data("translate");
if (dictionary.hasOwnProperty(key)) {
return dictionary[key];
}
});
};
// Swap languages when menu changes
$("#lang").on("change", function () {
var language = $(this).val().toLowerCase();
if (dictionary.hasOwnProperty(language)) {
set_lang(dictionary[language]);
}
});
// Set initial language to English
set_lang(dictionary.english);
});
1- I would like to improve this same code to change some images too (src), how can I do it?
2- is it possible to simplify this code? It´s very difficult to a newbie understand this kind of code: functions within functions... ugh !!! (have a lot to study)
Thanks in advance.
P.S. This is the link to the original post: jQuery language switcher
I believe that something like this would do the trick:
// Some variables for later
var dictionary, set_lang;
// Object literal behaving as multi-dictionary
dictionary = {
"english": {
"_hello": "Hello",
"_january": "January"
"_imgSrc": "myStuff/img/imageEn.png" //added as a example to image change
},
"portuguese": {
"_hello": "Oie",
"_january": "Janeiro"
"_imgSrc": "myStuff/img/imagePt.png" //added as a example to image change
},
"russian": {
"_hello": "привет",
"_january": "январь"
"_imgSrc": "myStuff/img/imageRu.png" //added as a example to image change
}
};
$(function () {
// Lets be professional, shall we?
"use strict";
// Function for swapping text
set_lang = function (dictionary) {
$("[data-translate]").text(function () {
var key = $(this).data("translate");
if (dictionary.hasOwnProperty(key)) {
return dictionary[key];
}
});
};
// Function for swapping images
set_lang = function (dictionary) {
$("[src-translate]").attr("src") === function () { //here is the problem, how to implement this?
var key = $(this).data("translate");
if (dictionary.hasOwnProperty(key)) {
return dictionary[key];
}
});
};
// Swap languages when menu changes
$("#lang").on("change", function () {
var language = $(this).val().toLowerCase();
if (dictionary.hasOwnProperty(language)) {
set_lang(dictionary[language]);
}
});
// Set initial language to English
set_lang(dictionary.english);