Like my work? If you're looking for a Bracknell Web Design Agency then drop us a line at 'Nine Four' and we can hook up for a chat.

A simple JavaScript to toggle page elements Friday February 16, 2007

No rocket science here but I thought I’d blog this for my own future reference. Just a handy little script to have about.

function toggle(elementID){
var target1 = document.getElementById(elementID)
if (target1.style.display == 'none') {
target1.style.display = 'block'
} else {
target1.style.display = 'none'
}
}

Just give the element you want to ‘toggle’ on and off an ID and then pass that to this script.

<a href="javascript: toggle('track_list_2');">Show/Hide</a>

That’s all. :)

Posted in: Code

 
Play online poker at Full Tilt Poker and PokerStars. The best online poker rooms still open to US players. welike-Poker.com provides unbiased and critical online poker room reviews.
  1. Matthew Pennell

    Feb 16, 12:05 PM

    $(this).toggle();

    Three cheers for jQuery! ;)
  2. Nathan Pitman

    Feb 16, 01:15 PM

    Neat, I hadn’t seen jQuery before. Thanks for the pointer Matthew.
  3. Andrew Strachan

    Feb 17, 04:28 PM

    Thanks – just what i was looking for.

    Though there is a typo in line 4 – it should read ” target1.style.display = ‘block’ ”

    I’m not being picky – You already knew that!
  4. Pawel Grabowski

    Feb 18, 02:53 AM

    Aye, cheers Nathan, works like a charm.
  5. Nathan Pitman

    Feb 19, 02:28 PM

    @Andrew, that should be corrected now. Thanks for the heads up RE the typo.
  6. Nathan Smith

    Feb 20, 03:59 AM

    You could make this slightly more versatile by setting the style to target1.style.display = ‘’ (empty). When left empty, the element will inherit the default display value for that element. Div becomes block, span becomes inline, and tables (which can be funky in cross-browser situations) will display correctly. If you set a table to display:block, it will look messed up in some browsers but not in others.
  7. Nathan Pitman

    Feb 20, 09:43 AM

    @Nathan, that’s a great little tip. Thanks for pointing that out, I wasn’t aware that table display could get funky when set to display: block. :)
  8. karmoosh

    Oct 4, 06:04 PM

    Neat, I hadn’t seen jQuery before. Thanks for the pointer Matthew.
  9. tenks natran

    Oct 21, 06:04 PM

    toogle js code very goods;
    Nathan, that’s a great little tip. Thanks for pointing that out, I wasn’t aware that table display could get funky when set to display: block. :)
  10. Max

    Nov 18, 09:14 AM

    Hey thanks, really useful.
Leave your comments
name:
email: Gravatar enabled.
http://
Format your message with Textile.
Remember

related

recently

The 10 most recent articles.