best javascript toggleDiv function ever

Everyone has a javascript toggleDiv function somewhere, but this is the cleanest one you will ever see

All this is is an expand and collapse of whatever you want it to expand/collapse - it is made for divisions with the 'block' declaration, but could also be used for inline elements if you simply changed it to 'inline' 

function toggleDiv(divid){
  var div = document.getElementById(divid); = == 'block' ? 'none' : 'block';}

Basically it is just a condensed if/then statement.  Keep in mind it will only work on the very first click if you already have 'display' set to 'block' or 'none' at first, otherwise it will take 2 clicks.  It is about as simple as it gets.

Comments (1) -

  • using none and block wont properly expand and collapse you need to use 'none' and  ''. especially if you want to apply the function to elements other than div.  and its nice not to limit the function to one element or require an id when you might already be working directly with an element already.

    try something like this. its clean and allows any number of arguments mized id's and actual nodes

    This one wont make you have to click it twice to get the desired affect the 1st time either

    *i just typed this here not actually ran it so if there is a typo dont yell. this should give the right idea anyway

    function toggle(){
      //jeremy cumoletti
      numElements = arguments.length;
      for(i=0;i<numElements; i++){
          toggleThis = document.getElementById   (arguments[i]);
          toggleThis = arguments[i]; ='none' ? '' : 'none';

Pingbacks and trackbacks (1)+

Add comment