Results 1 to 3 of 3

Thread: How to toggle 1 element on and the other off simultaneously.

  1. #1
    Join Date
    Jun 2006
    Location
    Carmona, Seville, Spain.
    Posts
    66
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default How to toggle 1 element on and the other off simultaneously.

    I've been using this script for toggling elements on and off.

    <script type="text/javascript">
    <!--
    function toggle_visibility(id) {
    var e = document.getElementById(id);
    if(e.style.display == 'none')
    e.style.display = 'block';
    else
    e.style.display = 'none';
    }
    //-->
    </script>

    BUT, I have TWO elements; 1 visible and 1 invisible and I'd like the following:

    onClick from one single link eg.<a href>: element 1 becomes visible and element 2 becomes INvisible at the same time. onClick again element 2 becomes visible and element 1 becomes INvisible etc. ie. only one element visible at any one time.

    Any ideas greatly appreciated.
    Last edited by green; 06-28-2007 at 03:03 PM.

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    This is not an endorsement or criticism of your existing code which I have used in only slightly modified form (comments within script blocks are not useful, but not really harmful for this type of script). Here it is doing just what I think you asked:

    HTML Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <script type="text/javascript">
    function toggle_visibility(id) {
    var e = document.getElementById(id);
    if(e.style.display == 'none')
    e.style.display = 'block';
    else
    e.style.display = 'none';
    }
    </script>
    </head>
    <body>
    <div id="el1">Hi</div>
    <div id="el2" style="display:none;">Bye</div>
    <a href="javascript:toggle();" onclick="toggle_visibility('el1');toggle_visibility('el2');return false;">Toggle</a>
    </body>
    </html>
    Note: The href is just a throwaway href and could be anything, just not nothing, unless it isn't there at all (having no href attribute would be fine). Having it this way gives the user a clue as to what clicking will do.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Jun 2006
    Location
    Carmona, Seville, Spain.
    Posts
    66
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default

    That works just about perfect. Thank you again, John.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •