DRY it up.
var b='block',h='none',m='message',f='fade';
function s(i,d){document.getElementById(i).style.display=d}
function open(){s(m,b);s(f,b)}
function close(){s(m,h);s(f,h)}
With the whitespace and proper variable names (to be passed to a minifier), this looks like:
var show = 'block', hide = 'none', message = 'message', fade = 'fade';
function setStyle(id, display) {
document.getElementById(id).style.display=display;
}
function open() {
setStyle(message, show);
setStyle(fade, show);
}
function close() {
setStyle(message, hide);
setStyle(fade, hide);
}
There are some best-practices which don't relate to the question but are worth considering if your project grows beyond this trivial situation:
- Use a minifier. My favorite is uglifyjs. This allows you to use meaningful variable names in your unminified code (like the second example). The minifier will output code more like (but probably even better than) the first example. Even with a minifier, keep thinking about what it can and cannot do - creating a private shortcut to a long public API like document.getElementById can aid the minification if you use that API frequently. Look at the minified code to make sure there isn't something you can do to optimize it.
- Separate your javascript into .js modules that are loaded separate from the page and asychrounously, if possible.
- Manage all your static assets (like the .js modules) so they have a long cache timeout - use the
Expires:
http header. Then change their URLs when they actually change. This way, clients can cache them indefinitely until you change them & then the client will immediately fetch a new version.
- Put discrete modules inside function wrappers, so that your variables don't conflict with other pieces of code - either your own or 3rd party modules. If you want to make a variable public, do it explicitly:
window.pubvar =