Posted By

kayue on 12/31/10


Tagged


Versions (?)

Toggle elements' display setting


 / Published in: JavaScript
 

  1. var type.value = 's';
  2.  
  3. // bad - redundent
  4. if ('s' == type.value) {
  5. cont.style.display = 'none';
  6. if (cont.shim) cont.shim.style.display = 'none';
  7. if (cats) cats.style.display = 'none';
  8. } else {
  9. cont.style.display = '';
  10. if (cont.shim) cont.shim.style.display = '';
  11. if (cats) cats.style.display = '';
  12. }
  13.  
  14. // good - take the only different
  15. var val = type.value === 's' ? 'none' : ''; // the only different
  16. cont.style.display = val;
  17. if (cont.shim) cont.shim.style.display = val;
  18. if (cats) cats.style.display = val;
  19.  
  20. // better - abstract a method
  21. var val = type.value === 's' ? 'none' : '';
  22. setDisplay(cont, val);
  23. setDisplay(cont.shim, val);
  24. setDisplay(cats, val);
  25.  
  26. function setDisplay(el, val) {
  27. if(el) el.style.display = val;
  28. }
  29.  
  30. // best - take a set of elements
  31. setDisplay([cont, cont.shim, cats], type.value === 's' ? 'none' : '');
  32.  
  33. function setDisplay(els, val) {
  34. // loop though the array
  35. for (var i = 0, len = els.length, el; i < len && (el = els[i]); i++) {
  36. el.style.display = val;
  37. }
  38. }

Report this snippet  

You need to login to post a comment.