this is my simple javascript function to switch colors and it works fine , but as far as i need to enable jquery or mootools in my website then its better to have this function modernized
function changeThemeColor(color)
{
switch(color)
{
case "style1":
default:
document.getElementById('CSSfile').href = 'css/style1.css';
setCooki开发者_开发技巧e('ThemeColor','style1',7);
break;
case "style2":
document.getElementById('CSSfile').href = 'css/style2.css';
setCookie('ThemeColor','style6',7);
break;
}
}
i know this maybe a huge quest but i really need to convert this code either into jquery or mootools
If your code works, why slow it down be converting it to library code that will just convert it back to what you have?
If this is actually what your code looks like, you could get rid of some of the redundancy:
function changeThemeColor(color) {
document.getElementById('CSSfile').href = 'css/' + color + '.css';
switch(color) {
case "style1":
default:
setCookie('ThemeColor','style1',7);
break;
case "style2":
setCookie('ThemeColor','style6',7);
break;
}
}
The style2
is sending 'style6'
to setCookie()
. If that's a mistake, and it should be sending 'style2'
, you could further reduce it.
function changeThemeColor(color) {
document.getElementById('CSSfile').href = 'css/' + color + '.css';
setCookie('ThemeColor', color, 7);
}
For MooTools:
function changeThemeColor(color)
{
switch(color)
{
case "style1":
default:
$('CSSfile').set('href','css/style1.css');
Cookie.write('ThemeColor','style1',{'duration':7});
break;
case "style2":
$('CSSfile').set('href','css/style2.css');
Cookie.write('ThemeColor','style6',{'duration':7});
break;
}
}
As you can see, the edits are so small I wouldn't even bother implementing them if I were you. It's not going to make your site more futureproof either.
If you want to use jQuery change this
document.getElementById('CSSfile').href = 'css/style1.css';
to
$("#CSSfile").attr("href",'css/style1.css');
and if you want to change the color from a div is
$("#divId").css("color","#f0f0f0")
Sorry for my english, i am from Argentina
edit: http://plugins.jquery.com/project/Cookie Here you have a cookie's jQuery plugin
for mootools (or indeed, jquery) i'd create a map of styles instead and do something like this:
var changeThemeColor = function(colour) {
var colours = { // set your mapping here.
style1: "style1",
style2: "style6"
}, style = colours[colour] || colours['style1']; // default to style1 if not mapped
document.id("CSSfile").set("href", "css/"+style+ ".css");
Cookie.write("ThemeColor", style, {
duration: 7,
path: "/"
});
};
trying to make it more modular/pattern based so it can easily support adding new styles in the future. the best way is to have this via an options
var as second argument where you can overwrite (externally) the default mapping and internally, do Object.merge()
.
精彩评论