3

How would I make this code smaller? Maybe a toggle, but people were saying this was easily done in jQuery. But the problem is that I am not a fan of using jQuery for just one thing in my code.

function open() {
document.getElementById('message').style.display='block';
document.getElementById('fade').style.display='block';
}

function close() {
document.getElementById('message').style.display='none';
document.getElementById('fade').style.display='none';
}
user1431627
  • 805
  • 1
  • 12
  • 30

5 Answers5

4
var message = document.getElementById('message'),
    fade = document.getElementById('fade');

function open() {
    message.style.display = fade.style.display = 'block';
}

function close() {
    message.style.display = fade.style.display = 'none';
}

Or:

function toggle() {
    var message = document.getElementById('message'),
        fade = document.getElementById('fade'),
        currentdisplay = getComputedStyle(message, null)['display'];

    if(currentdisplay == 'block' || currentdisplay == 'inline')
        message.style.display = fade.style.display = 'none';
    else
        message.style.display = fade.style.display = 'block'; /* or inline */
}

Or:

function toggle() {
    var currentdisplay = getComputedStyle(arguments[1], null)['display'],
        i,
        newdisplay;

    if(currentdisplay == 'block' || currentdisplay == 'inline')
        newdisplay = 'none';
    else
        newdisplay = 'block';

    for(i = 0; i < arguments.length; i++)
        arguments[i].style.display = newdisplay;
}

var message = document.getElementById('message'),
    fade = document.getElementById('fade');

toggle(message, fade); /* hide */
toggle(message, fade); /* show */

document.body.onclick = function(){
    toggle(message, fade);
}


Toggle Example:

http://jsfiddle.net/djHTq/

xandercoded
  • 33,178
  • 5
  • 73
  • 87
  • +1 even though there are more lines of code, this is definitely an improvement, since it means you don't need to get `message` and `fade` elements from the DOM everytime you call `open` and `close`. – lbstr Jun 26 '12 at 23:00
4

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 =
Julian
  • 2,729
  • 19
  • 30
  • 1
    How is calling the same function twice DRY? – Niet the Dark Absol Jun 26 '12 at 23:02
  • 1
    251 vs 265 bytes. Not that much diffrence :) – user1431627 Jun 26 '12 at 23:58
  • this is bad development code ... that is what minifiers are for! http://jscompress.com/ – xandercoded Jun 27 '12 at 00:12
  • Yes, I originally coded it assuming it'd be wrapped in a function & minified - as is usual in my environment. But then edited it smaller in response the complaints about it still being big. Can't please 'em all! – Julian Jun 27 '12 at 00:13
  • I'd recommend reverting the changes. Obfuscated variable names make it a lot harder for people trying to learn from examples. – Kevin Ennis Jun 27 '12 at 00:16
  • 1
    Tips to OP (generally everyone). If you make a shorthand for `document.getElementById`, please make it global and use `$` or `_` instead of `g`. Better to maintain. – Jason Stackhouse Jun 27 '12 at 00:16
  • Should I use a var or a function for that, officer master brain? – user1431627 Jun 27 '12 at 00:18
  • So I should not do as @Julian ... in a `var`? I called him that because he sounded really wierd when saying that - It dose not make sense – user1431627 Jun 27 '12 at 00:23
  • the length of your variable names should not be a deciding factor when optimizing code. as long as they're semantic you're good. – xandercoded Jun 27 '12 at 00:24
  • I would love to use C++ instead of JavaScript for webprogramming. – user1431627 Jun 27 '12 at 00:29
  • @user1426486 - nice tip, I hadn't heard of that before. I was going to do as you suggest, but then realized I had already obviated the need for any such and just took out the shortcut altogether. – Julian Jun 27 '12 at 04:21
  • @user1431627: When java and javascript landed in the same release of netscape (showing my age) I immediately gravitated toward java and spurned javascript. How foolish I was. Now I love javascript and haven't touched java in ages. Drink the cool-aid, take the red pill, etc. The sooner you learn to love it, the happier you'll be. It isn't going away. – Julian Jun 27 '12 at 05:05
  • @Julian I do not like the name JavaScript. JavaScript even looks more like C++ than Java. Makes no sense. – user1431627 Jun 27 '12 at 06:54
  • @user1431627 I hear you, but the fact remains, it isn't going away. http://coffeescript.org/ makes it a lot more palatable - dare I say pleasurable. Another promising (but not there yet) cure for the javascript blues is http://www.dartlang.org/ – Julian Jun 27 '12 at 15:02
3
var toggle = function(doc){
    var $ = doc.getElementById, message = $('message'), fade = $('fade'), open = true;
    return function(){
        var display = open ? 'none' : 'block';
        message.style.display = display;
        fade.style.display = display;
        open = !open;
    } 
}(document);

toggle(); // Hide both elements
toggle(); // Show both elements. Rinse and repeat.
Kevin Ennis
  • 13,330
  • 2
  • 39
  • 41
2

Avoids polluting global scope:

(function() {
    var msgstl = document.getElementById('message').style,
        fdestl = document.getElementById('fade').style;
    window.open = function() {msgstl.display = fdestl.display = "block";};
    window.close = function() {msgstl.display = fdestl.display = "none";};
})();
Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540
2

One thing is you can create a helper function for setting styles on elements. This would be useful in cases where you need to set many different elements.

function setStyle(element, style, value) {
    document.getElementById(element).style[style] = value;
}
function open() {
    setStyle('message', 'display', 'block');
    setStyle('fade', 'display', 'block');
}
function close() {
    setStyle('message', 'display', 'none');
    setStyle('fade', 'display', 'none');
}

You may also want to set the elements to variables if you work with the elements often enough.

var message = document.getElementById('message'), fade = ...
John Kalberer
  • 5,310
  • 1
  • 17
  • 26