with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

Seven ways to toggle an element with JavaScript

Friday, February 10th, 2006

There are litterally an unlimitted number of ways to toggle an element’s display with JavaScript. Some, more useful than others. Dating back to the late nineties, toggling is perhaps the oldest trick in the book within JavaScript development. However, to this day, it still proves itself useful as hiding/showing elements can improve user interaction (when done tastefully).

Anyway, here are seven ways toward achieving just that.

The bottom line

First off, this is perhaps the simplest and shortest way to toggle.

toggling the short way

// showing
document.getElementById('element').style.display = '';
// hiding
document.getElementById('element').style.display = 'none';

So let’s make this into a function that’ll get the job done real quick like:

show? or hide?

function toggle(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}

Well that was easy. But we can also go ternary style.

toggling ternary style

function toggle(obj) {
	var el = document.getElementById(obj);
	el.style.display = (el.style.display != 'none' ? 'none' : '' );
}

Cool. Hey, ever heard of the dollar function? If that’s sittin’ around somewhere, let’s use it!

toggling with the ternary dollar

// our dollar function
function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}
// and now our improved toggler!
function toggle(obj) {
	var el = $(obj);
	el.style.display = (el.style.display != 'none' ? 'none' : '' );
}

Cool. Now that we’ve got this thing nice and compact… can’t we do anything else to make it cool? Why, of course. Let’s say, instead of limitting it to just one object, let’s say “unlimitted.”

toggling multiple objects

function toggle() {
	for ( var i=0; i < arguments.length; i++ ) {
		$(arguments[i]).style.display = ($(arguments[i]).style.display != 'none' ? 'none' : '' );
	}
}

Sweet. Now that looks nice and sexy (quite personally, I think it’s the sexi’est’). But let’s see if we can extract any of these into “showing” versus “hiding” using an object literal.

separating showing and hiding

var toggle = {
	show : function(obj) {
		document.getElementById(obj).style.display = '';
	},
	hide : function(obj) {
		document.getElementById(obj).style.display = 'none';
	}
};

Alright alright alright, I can dig that. But what happened to using our dollar buddy? Surely we can get that back in the mix.

separating showing and hiding

var toggle = {
	show : function(obj) {
		$(obj).style.display = '';
	},
	hide : function(obj) {
		$(obj).style.display = 'none';
	}
};

Ok, why not even give it the flexibility of passing in as many arguments as we want to either? Ok, no problem.

separating showing and hiding

var toggle = {
	show : function() {
		for ( i=0; i < arguments.length; i++ ) {
			$(arguments[i]).style.display = '';
		}
	},
	hide : function() {
		for ( i=0; i < arguments.length; i++ ) {
			$(arguments[i]).style.display = 'none';
		}
	}
};

Cool. That pretty much covers it. You can view the multiple toggler function in action

76 Responses to “Seven ways to toggle an element with JavaScript”

  1. Justin Perkins

    Nice little demo, way to break it down.

  2. tobto

    I like such a little thingies usefull for all kind of web-developers. Go on!!

  3. jordan

    If you’re looking for something to do some real JS cleanup work on, download the BBC widget for Dashboard. The code is an utter mess.

    There’s onclick/onmouseover/onmouseout stuff all through the source, an initialise-on-load bit, and the coding style is all over the place, even though it appears to be written by just one guy.

    I’m working through it right now, but I don’t know enough JS to clean it up completely yet. For the moment I’m working on just getting the code back in to it with a consistent and clean formatting.

  4. Jim A.

    It becoming a vicious cycle this is…I visit Dustin’s site, I find a better version of something I was doing, I edit my common.js to put in the better version, I save and FTP my common.js–then I visit Dusitn’s site again where I see something else to change…

  5. Dustin Diaz

    Jim, just out of curiosity, which one did you end up going with?

  6. Jim A.

    number 7, “separating showing and hiding”

    I like it for its OOPness, JSON syntax, and separate methods.

    Another cool version would use the “this” keyword and could be added to an object as its toggle method.

  7. leevi graham

    Great article Dustin. I love the way you evolved the code from step to step.

    Personally I like to toggle class names of an element instead of its display properties. This provides much more flexibility as you have access to all the css display styles, like inline, table-row etc.

    Of course the code is a little longer due to the need for addClass(), checkClass() and swapClass() methods.

    Thanks again

  8. Zach Harkey

    Toggling element visibility is a great feature to have, and this article does a great job of laying out many possibilities, but what I still can’t seem to find anywhere is a solid way to maintain a toggled state across a page load.

    For example, I want to provide a menu of advanced administrative options across the top of the page for admins logged into a CMS. Since the menu takes up screen space and isn’t always needed, I’m using the standard toggle() function (from your Top 10 javascript functions list) and it does a great job of instantly hiding/showing the menu.

    The problem is when I go to another page, the menu doesn’t remember its current state, always reverting to the default state which greatly reduces the usefulness of the tool. (I call it my little Momento menu.)

    I’ve seen a couple hints of solutions on this site and elsewhere on the web (cookies etc.) but I’d give my left arm for a detailed how-to that pulls all of these features together.

  9. Dustin Diaz

    Zach, you are indeed need to use cookies (if you’re looking for a pure javascript solution).

    You can use a combination of the getCookie, setCookie functions from that top ten list. And within toggling elements, you’ll want to set a cookie storing information about which element it is, and what state it’s in (shown, or hidden).

    Experiment a little before the answer gets too obvious. It’s good for ya :)

  10. ozh

    Doesn’t the 5th function misses its argument ? i.e. toggle(argument) instead of toggle() ? Nice stuff by the way.

  11. jean-marc

    Hello,

    I had found the ternary toggling style somewhere on this website. By now seven ways to play with. That is a good idea for a beginner like me : to put one thing in severals ways. Thank you !

  12. Moe

    I’m surprised to see that $(obj).style.display = ”; works, I use $(obj).style.display = ‘block’; or $(obj).style.display = ‘inline’; to show an element, because values in CSS are display:none; , display:inline; or display:block; but in my opinion it makes no sense to write display:; so I won’t set an empty string with $(obj).style.display.

  13. Lance Fisher

    Hey Zach,

    Another option (which is not all javascript but would probably be more secure) is to use a server-side scripting language (PHP, ASP.NET, etc.) to only write out the admin menu items if the user is logged in. You don’t want someone without the right to access the menu to be able to poke around in the source and find the admin pages, especially if the admin pages don’t check the user’s rights.

  14. Jason Beaird

    Fun. <looks around for something to toggle /’

  15. Jason Beaird

    Er…that was supposed to be a &gt; :(

  16. Jim A.

    @Lance Fisher, Zach isn’t talking about hiding/showing an admin user via JS based on whether the user should have access to it. He is talking about a menu that only admins get, but he wants to be able to tuck it out of the way when that admin user isn’t in need of it.

  17. Dustin Diaz

    @ozh: arguments is a property you have access to within the function. It’s not something you pass to it. Try it out. It does indeed work :)

    @Moe: by setting the display to blank ”, you’re letting the element shape back to its normal form. if it’s block, then it goes block. if it’s inline, it goes inline. if it’s table-row, it goes to table-row… catching the pattern eh? It just simplifies the process :)

  18. Project :: penkiblog » 本日書籤 (偷懶版)

    [...] http://www.dustindiaz.com/seven-togglers/ [...]

  19. rita

    hi,

    splendid work!!!

    thanks for given such a good ref.

  20. jasson

    Great set of functions, it works beautifully for hiding multiple items.

    I’d like to have an element hide before the page is displayed and then reveal it when a user clicks a link.

    When I sent the CSS to “display: none;” I can’t get the element to toggle. I’ve tried a few other ways, but they always show the element briefly and then hides it after the page has finished loading.

    Any ideas?

  21. RegularJoe

    I am complete novice so seeing those functions, without an “example” call is confusing me.
    I have used the toggle (No 2 in list) to show hide a DIV tag with an ID=help
    but I have to do

  22. Cailean

    I have several toggled elements in various pages, and in IE I have this issue where elelments that follow the ‘togglers’ get all mis-aligned after toggling…
    I noticed also that your example in IE leaves the ‘Paragraph 3′ text on the screen even after toggling. This would seem related to my problems… Any ideas?

  23. Sean C

    For those of you (including jasson) who noticed that the scripts do not work on the first try for elements that are originally display:none in CSS…

    This is because JS originally has the display set to the empty string (just ”), so it will not ==’none’.

    To get around this, I use the code:

    ////
    // If the element with the given id is display=’none’, will set it to inline. If set to anything else,
    // will be changed to showType. If showType is not set, it will default to inline.
    ////
    function toggleDisplay(id, showType){
    if(!showType){
    showType = ‘inline’;
    }

    // If object was originally display:none in the CSS, it will show the first time as just display==”, but the width will be 0.
    var obj = $(id);
    if((obj.style.display == ‘none’) || ((obj.style.display==”) && (obj.offsetWidth==0))){
    obj.style.display = showType;
    } else {
    obj.style.display = ‘none’;
    }
    }

    This works because when an element is display:none, the width will be 0 until it is set to some other display type.

    Obviously you can mix those principles into one of Dustin’s 7 functions… this is just one I wrote that I had laying around (not necessarily as good).

    Hope that helps!

  24. Utter

    Like jasson I have a requirement for having a page element hidden on page load but revealed by a click.

    But in order for the page to degrade correctly I don’t want to have to set the element with display: none; so that viewers with js disabled will get to see the elements that would otherwise be hidden.

    The only way round this I can see is to force the element display to none using js itself but this also causes all the togle scripts I’ve tried to fail.

    Does anyone know of a solution like this?

  25. Steven

    Great. Very clean. How can you pass different id’s to this function? Say you have a row, a hidden row, a row, a hidden row… and I want a link in each visible row to reveal the hidden row below without affecting the other hidden rows?

  26. Sean

    Great page! I am having a small problem with this type of script. I have a page that contains about 8 different layers all uniquely identified and I have a toggle script that functions perfectly. Now, I created a show all link to displays all layers and that also works. However, if a user toggles a layer after clicking the show all link, then uses the close all link to toggle all layers closed, the layer that was toggled while all where open requires two clicks to toggle at this point. Any ideas?

  27. Sean

    Hah! Got it! Nevermind.

  28. Tonstube » Blog Archive » Toggeln

    [...] Im dem Artikel “Seven ways to toggle an element with javascript” beschreibt Dustin (ein web developer für Yahoo) sieben Wege, wie man ein Element mittels Javascript “toggeln” kann (wer des Englischen mächtig ist hat das bestimmt schon aus dem Titel gelesen ). [...]

  29. Sujeet kumar

    Please Help
    How to on/off the capslock key through the javascript.
    You can directaly mail me on

    sujeet.kumar@ecotechservices.com

    Thanks in advance
    Sujeet

  30. arghhh

    can’t get the toggle multiple args to work…

  31. Dustin Diaz

    @arghh: Keep trying. Don’t give up :) Several people have got it working.

  32. Mans

    hi everybody:
    Hope I can find an answer her. I’m trying to hide and show a tree list. This can be easily done, but when I get to the point where the user will go to a diiferent page and make th ebrowser remember the expanded list, the problem starts. what i need to do is a similar tree to the one on http://dhtml-menu.com/tree-examples/tree-menuxp.html
    Here is my code:
    function storage()
    {
    old=”;

    }

    function menu(obj) {
    var el = document.getElementById(obj);

    if( obj == storage.old)
    {
    //we dont do anything here
    //alert(”they are equal “+ obj + ” and ” + storage.old);
    }
    else
    {
    //alert(”not equal: “+ obj + ” and ” + storage.old);
    el.style.display = ”;

    //now hide the old one
    var tmp=document.getElementById(storage.old);
    tmp.style.display=’none’;

    alert(”They are not equal: “+ el + ” and ” + tmp);
    storage.old = obj;
    }
    }

    You can remove th ecomments for debugging :P

  33. zlich

    saved my day!!! :)

  34. Ali

    does it really need seven ways? ;)
    nice any way! :)

  35. Palli

    Hey, that’s a really nice list. I have a small problem though. I have like a tree of employers under different sets of bosses. I click boss 1 and his staff opens up. That works perfectly. However, if I click another boss straight away, his staff opens as well but overlaps the old staff, making it look a real mess. Now I’m wondering if I can close all divs but the clicked one?

    There probably is a very simple solution but I’m a JS idiot so I can’t figure it out. Any help would be greeeatly appreciated!
    Thanks,
    -Palli

  36. OracleHome

    Hi,

    Thanks for the code examples.

    I previously used .style.visibility=’visible’; but wanted something that reclaimed the space on screen.

    Thanks
    Dan

  37. Seagyn

    Thanks Dustin, this helped me alot, I am a junior developer so needless to say I need to learn. But this helped me alot!

    Something you might want to do, and i dont know if one of your methods did this is to change from show to hide and visa versa when it is clicked. Alsdo to use and image. Mail me if you want to see what i did.

    Seagyn Davis

  38. Curious

    This was a really good breakdown. I applied these techniques to a div tag that was holding dynamic input fields that you can add/remove at will. Once I submit this form, it goes to a ‘Step 2′ page. If I return back (history.go(-1)) to the original page, Firefox keeps the div tags displayed, as well any input fields that I populated (i.e. how it looked before I was ready to submit the form). IE does not do this and ‘toggles off’ the div tags and loses my form field data - any ideas why? If so, how do I get IE to mimic Firefox’s behavior?

  39. Brandon

    Now I usually have a bone to pick with folks who muddle their content with code because it makes the jobs between designers and developers more difficult. But in a case where I am the designer and developer, I sometimes muddle my pie as I realize I’m in the real-world and I want to solve problems quickly. Here’s an example of what I’ve done in regard to this topic of toggling:


    Click for more Users

  40. Brandon

    Now I usually have a bone to pick with folks who muddle their content with code because it makes the jobs between designers and developers more difficult. But in a case where I am the designer and developer, I sometimes muddle my pie as I realize I’m in the real-world and I want to solve problems quickly. Here’s an example of what I’ve done in regard to this topic of toggling:

    <p id="allUsersToggle" class="allUsersToggleOn"> <a href="#" onclick="javascript:document.getElementById(’allUsersToggle’).className=’allUsersToggleOff’;document.getElementById(’allUsersInvestigator’).className=’allUsersOn’;">
    Click for more Users</a>
    </p>
    <div class="allUsersOff" id="allUsersInvestigator">
    <select name="investigator">
    <!– your code for a user list –>
    </select>
    <input type="submit" name="createNewUser" value="New Investigator">
    </div><!– End of ‘allUsersInvestigator’ –>

  41. Chris Ash, syd - Aust

    I thought this was meant to be a easy to understand toggle tutorial script. It just seems like you have made it too complicated…. and why dont you give a link to download the javascript … preferably a skeleton version..

    has anyone made a tutorial that is more simple ?

    Cheers

  42. glenn

    I want to have something like this to toggle a soccer league’s schedules(which would be in a table) when they click on the desired catagory(a header of mens, womens, etc.) it will display the table

    never used a lot of javascript, help! :)

  43. glenn

    for example:

    // showing
    document.getElementById(’table’).style.display = ”;
    // hiding
    document.getElementById(’table’).style.display = ‘none’;

    link
    table!!!

  44. Theodor Zoulias

    Well, these are not really seven ways to toggle an element, but seven coding styles using display=’none’. Lets see if we can find seven DIFFERENT ways to hide an element. :-)

    - style.display = ‘none’
    - style.visibility = ‘hidden’
    - style.width = ‘0px’; style.overflow = ‘hidden’
    - style.left = ‘-1000px’
    - style.zIndex = 0
    - style.opacity = 0
    - style.color = ‘white’
    - parentNode.removeChild(this)

  45. Laura

    Okay, I am a CSS person, and have been doing a sorta-toggle using the mouse over (event?) with just css. It only takes a few lines of CSS. Granted, there is a “hard” switch, as in no transition effects, but very similar to the end result of the example, except for the click (that’s an event, right?) I really need to learn javascript (DOM scripting?) But I find that most of the books I have bought are focusing on things I don’t care to know, like making an image gallery. Mostly I need it to help cover the gaps between browser CSS interpretation so that my presentation stays consistent, and tweak a little of my regular CSS stuff like for drop down menus, etc. Any suggestions? Any one want to volunteer to mentor?

  46. Matt

    Hey, thanks for the fabulous demo. I was looking at how to do something like this for work recently. I needed to see if a panel with objects in it was visible and if so, validate the data in the objects (textboxes).

    So, I tried your code. However, it did not work. I am now receiving a “pnlReview is null or not an object” error. Do you have any idea why this would be? I used the code you have here (subbing my object names, of course) and they are spelt right. CODE: if (doc.pnlReviewer.style.display != “none”) { /CODE is the line where it gives the error. Thanks!

    - M@C

  47. Puneet

    Thanks a lot !!
    Solved my problem in first go….

  48. Tvorba stránok

    Thanks for these solutions… btw u have something about object positioning there?

  49. no.good.at.coding

    Hi,

    I’ve to make a small tree menu that can be collapsed and expanded on clicking the title, kinda like the archived posts links in blogger.

    I haven’t actually done anything yet, was just wondering how to go about it.

    And also, how do you do that cool toggle thing with your code in the posts? The bouncing open/close? I tried to go through your page source but I couldn’t figure it out.

    Is there a JavaScript function you’re calling? When do you call it? Is there a onMouseClick() event somewhere? Am I in Kansas? Who am I? Help!

    Thanks.

  50. Kevin

    Was just wondering if anyone has managed to sort out the code for having a page element hidden on page load. I’ve been toying with the function for a little while and must be having issues…Unfortunately it’s not working for me. I’ve got no problem making it visible on page load, and having it disappear with a click… but I’d like it the other way around.

    any help? Thanks

  51. Steve

    Hi. I’d like to do something like what Kevin is asking; to have a div hidden on page load, and then have it toggle on and off (preferably sliding down and up). I’m incredibly novice when it comes to JavaScript, so I’d appreciate any practical advice.

    Also, being a novice, I have no idea how to implement any of the toggle functions discussed on this page. What does it take? Pasting the code between script tags doesn’t seem to cut it … so if someone could also let me know how to implement the examples on this page, I’d be grateful.

  52. David

    Hi. Excellent Work!
    I have a problem that i need to resolve asap. Any help will be greatly appreciated:

    In my page i have a main column filled with a list of 30 divs. Some divs share the same id, making sets. In the sidebar i have a list of checkboxes, each one related to a set. I need to toggle all the divs under the same id when checking the relevant checkbox.. I tried using a basic toggle script but it only toggles the first item of each set. How can i do a ‘cycling’ that allows me to toggle *all* the items under the same id?

    thank you very much, excuse the newbieness..

  53. » Abrir/Fechar elementos usando Javascript e CSS - IvoGomes.com

    [...] O Dustin Diaz mostra 7 maneiras diferentes de abrir/fechar (toggle) um elemento usando Javascript. [...]

  54. Viji

    Hi,
    This code was useful. I have requirement like showing Questions and Answers. There are around 20 questions. And when i click the Finish button, I should show the answers. The toggle function is working fine for me.
    But the problem is getElementById function returns only the first element.
    I gave the same div id for all questions and same div id for all answers.
    How can i achieve this?

  55. stu

    Thanks for the great code, but as a newbie how can this be adapted it so that if i have 4 buttons and 4 divs and i just want button 1 to toggle div1 on and off while turning off div2, div3 and div4 and button 2 to to toggle div2 on and off while turning off div1, div3 and div4 etc

    any help would be very appreciated
    stu

  56. ujisama

    yo “viji”. you can’t have duplicate id’s in your document. that’s why your getting unexpected results. i haven’t played with this code yet but it seems you would pass a list of arguments (id1, id2, id3, etc…) in order to toggle multiple items. if you give all of your elements the same id it will either fail completely or just do funky stuff.

  57. Johan

    Thanks, this really helped me a lot, although I had to use the getElementsByName method in my code to get it to work.

  58. Shafiq Rehman

    Thanx man, this really helps me a lot

  59. Larry

    I have something similar to the problem of initializing the display = ‘none’. If I do this, it never toggles. However, this is not quite like Sean’s case, where he’s just toggling the display on and off. In my case, I toggle some checkboxes on/off depending on a dropdownlist value. If it’s “Note” then I want the checkboxes to not appear, otherwise appear.

    Here’s a snippet (written in asp.net 1.1):

    ‘ Initialize the checkbox to display = ‘none’
    If ddlFieldTypes.SelectedItem.Text = "Note" Then
    chkSortField1.Style.Add("display", "none")
    End If

    ‘ From within the javascript function
    var ftype = document.getElementById('" & ddlFieldTypes.ClientID & "');
    var fname = ftype.options[ftype.selectedIndex].text;
    var fsort1 = document.getElementById('" & chkSortField1.ClientID & "');

    if (fname=='Note') {
    fsort1.style.display = 'none';
    } else {
    fsort1.style.display = '';
    }

    Again, if I don’t initialize the checkbox display to none, then everything works fine.

    I have no idea how to use Sean’s suggestion here. Any clues??

    Thanks,
    Larry

  60. Larry

    I’m having a similar problem to what Sean explains. However, I have no idea how to incorporate his “solution” into my code. I’m not just toggling the display on and off. Instead, I toggle the display on or off depending on what selection a user makes in a dropdown box. Everything works fine unless I initialize the display to none.

    Using alerts I verified that the display WAS being set to “inline”, yet the controls remained invisible.

    Any clues???

  61. Brady

    Hi,

    ok to start off with i do not know how to write JS. I basically write Coldfusion pages and i am having a problem trying to get the following code to work. Imagine this: At the top of the page i have a header and under that i have some text with all of my links e.g. contatc us, services ect….. ok. now as a part this page i have a menu on the left of the page displying all the categories of the items i have and then when i click on the category it displays all of the subCategorys. You may be asking what the hell is the problem then, well because the menu at the TOP of the page has a mouse over function and mouse out function it uses JS but the menu on the left uses JS as well. i thought it wouldnt be a problem to get this to work however when i click a link on the LEFT menu , with all the categories, it removes the entire top menu and it vanishes completley. Can someone please tell me if it is because they are both using DIV’s (they are using different ID’s) and belive me their is heaps of them and it took me ages to get this to work as it is and i would prefer to not have to remove the entire lot. The below code is all the code in the JS file. HELP PLASE.

    
    sfHover = function() {
    	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
    	for (var i=0; i";
       } else {
    	  CollapseEvery();
          obj.style.display="block";
          key.innerHTML="";
       }
    }
    
    function Expand() {
       divs=document.getElementsByTagName("DIV");
       for (i=0;i";
       }
    }
    
    function Collapse() {
       divs=document.getElementsByTagName("DIV");
       for (i=0;i";
       }
    }
    
    function CollapseEvery() {
       divs=document.getElementsByTagName("DIV");
       for (i=0;i
  62. Brady

    no problem just copied your number 2 and changed a little bit and all fixed. May i say for a novice to JS but an expert in HTML & CFML this is a great site. Great Work.

  63. Tamir

    Great code and examples. Haleluya.
    How do you do the fansy toggling on this page ?

  64. lothar patten

    this is a whole new way of seeing a website fashion for me.I’ve been looking for new ways of expression on different websites.I like this one alot.lothar patten.

  65. rizzah

    Just wondering if anyone has an answer (or a link to an answer) for Palli’s question from August 16th, 2006 at 4:43 am?
    ———–
    Hey, that’s a really nice list. I have a small problem though. I have like a tree of employers under different sets of bosses. I click boss 1 and his staff opens up. That works perfectly. However, if I click another boss straight away, his staff opens as well but overlaps the old staff, making it look a real mess. Now I’m wondering if I can close all divs but the clicked one?
    ————–

    I’d love to use these expand/collapse scripts but I need them to open and close in relation to each other. I.E. if you open one, all the other close.

    If anybody knows of a solve, or even knows of search terms for me to use, it would be greatly appreciated.

  66. karmoosh

    good lessom
    i want more
    thank you

  67. Igor

    instead of using test1, test2 etc… I use
    box1 with
    <div id="box1" style="display: none; ">
    It works with IE5.5 [not tested prior] and FF, but FF gives a warning
    Warning: ‘undefined’ found where ‘:’ expected. Declaration ignored.
    Row: 0

    Any idea?

    - Igor

  68. best

    I thought this was meant to be a easy to understand toggle tutorial script. It just seems like you have made it too complicated…. and why dont you give a link to download the javascript … preferably a skeleton version..

  69. chis

    hi I’m a junior developer and a complete newbie to JS. I hava been looking for a solution for toggling table rows and while you have listed the function here, could someone please tell me how to call the function froma select box? Any help greatly appreciated.

  70. Disapointed

    This is great but you have to have JS knowledge to know what to do with those snipets and know how to use/apply them. As a JS noob, I’m … well… no where further forward to what I’m trying to do (aka: useless!)
    This would have been so much better if the author had actually explained what was going and give a little simple example, then the tutorial would have been top marks… :-(

  71. Jason

    Hi,
    Great post. Quite a few readers are wondering in the comments how to hide a div on page load. AFAIK, all you have to do is set the div’s display attribute to none, like so:

    <div id="calendar_add" style="display:none">

    Works fine in both IE and Firefox.

  72. aswath

    if( document.g.category.checked==true){
    document.getElementById(’modify_txt’).style.display= ‘block’;//so as to make a controle appear
    }

  73. aswath.n.s

    i have a question..

    Q: i have 2 textbox.. 2 radiobutton.. on click of a radiobutton appoirate textbox must appear.. by default both textbox would be invisible..

    thanks in advance..

  74. FactoryMatt

    Thanks, but you should probably include both visibility and display… older browsers ate still out there.

  75. red

    hey dustin,

    nice job and I think it will be muy useful. I just picked up CSS a week ago (to do my wife’s website) and now I’m at the stage where I need to toggle ‘active’/'inactive’ classes selectively on multiple kinds of tags. Your page comes about as close as any I’ve seen to that task. I’ll send an ‘argghhhhhh report’ as soon as I sort it all out.

    What I really wanted to comment on is the quality of your posted comments. I don’t usually print out a whole page like this along with its comments, but in this case I did. Most pages, posters are either trying to be wayyyy to geekish or, are so completely um-duh, its a pure waste of inkwidth and paperwidth to print them. But you guys (newbie wirehead) all seem to say things that enhance Dustin’s work. Thanx much - nice job. - red

  76. Kyle Simpson

    @Zach- Try using window.name to stuff “session state” stuff, like the state of your collapsed menus, etc.

    Basically, you can enter any string you want into the window.name property, and it will still be there for retrieval when your page refreshes.

Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScript™ is a powerful language, allowing you to add an impressive array of dynamic functionality to otherwise static web sites. But there is more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities, and by applying OOP principles, best practices, and design patterns to your code, you can make it more powerful, more efficient, and easier to work with alone or as part of a team."

Buy JS Design Patterns from Amazon.com Buy JS Design Patterns from Apress

All content copyright © 2003 - 2009 under the Creative Commons License.

Archives | Blog Search