SitePoint Sponsor

User Tag List

Results 1 to 11 of 11

Thread: Show/Hide Divs

  1. #1
    SitePoint Zealot samg914's Avatar
    Join Date
    Nov 2009
    Location
    Boston, MA
    Posts
    132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Show/Hide Divs

    I need to show/hide certains divs when a link is clicked.

    These are my divs:

    div1
    div2
    div3
    div4
    div5

    I will have several links. Depending on which link is clicked it will hide/show several divs simultaneously. For example, if link1 is clicked it will hide div1, div2 and div3 and show div4 and div5.

    Thanks,

    Sam

  2. #2
    Forums Designer
    Join Date
    Jun 2004
    Posts
    422
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try something like this:
    Code:
    <a href="javascript:void(0);" onclick="showDivs(1); return false;">link 1</a>
    <a href="javascript:void(0);" onclick="showDivs(2); return false;">link 2</a>
    etc...
    
    <div id="div1" style="display: none;">div 1</div>
    <div id="div2" style="display: none;">div 2</div>
    etc...
    
    <script>
    function showDivs(start)
    {
     var div;
     while((div = document.getElementById('div' + start)) !== false)
     {
      div.style.display = (div.style.display == 'none') ? '' : 'none';
      start ++;
     }
    }
    </script>
    That simple function's first parameter is a starting div number. It will show all divs starting with that one until the last one.

  3. #3
    SitePoint Zealot samg914's Avatar
    Join Date
    Nov 2009
    Location
    Boston, MA
    Posts
    132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by CyberAlien View Post
    Try something like this:
    Code:
    <a href="javascript:void(0);" onclick="showDivs(1); return false;">link 1</a>
    <a href="javascript:void(0);" onclick="showDivs(2); return false;">link 2</a>
    etc...
    
    <div id="div1" style="display: none;">div 1</div>
    <div id="div2" style="display: none;">div 2</div>
    etc...
    
    <script>
    function showDivs(start)
    {
     var div;
     while((div = document.getElementById('div' + start)) !== false)
     {
      div.style.display = (div.style.display == 'none') ? '' : 'none';
      start ++;
     }
    }
    </script>
    That simple function's first parameter is a starting div number. It will show all divs starting with that one until the last one.
    Hi Cyber Alien,

    This code looks good. However it doesn't seem to work properly. Not sure what the problem is, as my understanding of javascript is minimal.

  4. #4
    Forums Designer
    Join Date
    Jun 2004
    Posts
    422
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I've made a error, it should check if variable div is null, not false. Change while(...) line to this
    Code:
    while(div = document.getElementById('div' + start))

  5. #5
    SitePoint Zealot samg914's Avatar
    Join Date
    Nov 2009
    Location
    Boston, MA
    Posts
    132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by CyberAlien View Post
    I've made a error, it should check if variable div is null, not false. Change while(...) line to this
    Code:
    while(div = document.getElementById('div' + start))
    1 <script>
    2 function showDivs(start)
    3 {
    4 var div;
    5 while(div = document.getElementById('div' + start))
    6 {
    7 div.style.display = (div.style.display == 'none') ? '' : 'none';
    8 start ++;
    9 }
    10 }
    11 </script>


    Line 4 is giving me an unspecified error.

  6. #6
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,527
    Mentioned
    84 Post(s)
    Tagged
    4 Thread(s)
    Let's start with an HTML page that has links and the divs.

    Code html4strict:
    <ul id="items">
        <li><a href="#apple">Apple</a></li>
        <li><a href="#banana">Banana</a></li>
        <li><a href="#grapefruit">Grapefruit</a></li>
        <li><a href="#noisy">Noisy</a></li>
        <li><a href="#watermelon">Watermelon</a></li>
    </ul>
    <div id="apple">
        <p><a href="http://lifehacker.com/5804509/how-to-split-an-apple-without-a-knife">How to Split an Apple Without a Knife</a></p>
    </div>
    <div id="banana">
        <p><a href="http://lifehacker.com/5349295/make-quick-ice-cream-with-only-frozen-bananas">Make Quick Ice Cream with Only Frozen Bananas</a></p>
    </div>
    <div id="grapefruit">
        <p><a href="http://www.npr.org/2011/04/18/135468567/repelling-bugs-with-the-essence-of-grapefruit">Repelling Bugs With The Essence Of Grapefruit</a></p>
    </div>
    <div id="noisy">
        <p><a href="http://www.youtube.com/watch?v=eHnnGHgeyC0">Noisy fruit and veggies - Synesthesia</a></p>
    </div>
    <div id="watermelon">
        <p><a href="http://www.bbc.co.uk/news/world-asia-pacific-13421374">China farmers face 'exploding' watermelon problem</a></p>
    </div>

    You don't want the content to be invisible when someone visits with no scripting, so we'll use scripting to hide the divs as the page is loading.

    Code css:
    .hidden {
        display: none;
    }

    Scripts should be put at the bottom of the page, just before the </body> tag. That's both for performance reasons, and because it allows us to work directly with page elements before the load event occurs.

    Code html4strict:
    ...
    <body>
        ...
        <script src="script.js"></script>
    </body>
    </html>

    This script is attached to the tabs section, so that we can easily work with the clicked link:

    Code javascript:
    tabs.onclick = function (evt) {
        evt = evt || window.event;
        var link = evt.target || evt.srcElement,
            links,
            i,
            target;
        if (link.nodeType === 1 && link.nodeName === 'A') {
            ...
        }
    };

    When one of the links is clicked, we want to hide the target div of all of the other links. If the link is for the one that was clicked, we show that one instead. And lastly, we return false to prevent the web browser from doing its default behaviour of loading the link.

    Code javascript:
    links = this.getElementsByTagName('a');
    for (i = 0; i < links.length; i += 1) {
        target = document.getElementById(links[i].href.split('#')[1]);
     
        if (link !== links[i]) {
            target.className = 'hidden';
        } else {
            target.className = '';
        }
    }
    return false;

    Here's a simple test demo of the technique, which is flexible and can be expanded to meet many different types of needs.

    This test code is inline for the sake of posting here, but the css and javascript should normally be placed in a separate external file.

    Code javascript:
    <html>
    <head>
    <style type="text/css">
    #tabs li {
        display: inline;
    }
    .hidden {
        display: none;
    }
    </style>
    </head>
    <body>
    <ul id="tabs">
        <li><a href="#apple">Apple</a></li>
        <li><a href="#banana">Banana</a></li>
        <li><a href="#grapefruit">Grapefruit</a></li>
        <li><a href="#noisy">Noisy</a></li>
        <li><a href="#watermelon">Watermelon</a></li>
    </ul>
    <div id="apple">
        <p><a href="http://lifehacker.com/5804509/how-to-split-an-apple-without-a-knife">How to Split an Apple Without a Knife</a></p>
    </div>
    <div id="banana">
        <p><a href="http://lifehacker.com/5349295/make-quick-ice-cream-with-only-frozen-bananas">Make Quick &#8220;Ice Cream&#8221; with Only Frozen Bananas</a></p>
    </div>
    <div id="grapefruit">
        <p><a href="http://www.npr.org/2011/04/18/135468567/repelling-bugs-with-the-essence-of-grapefruit">Repelling Bugs With The Essence Of Grapefruit</a></p>
    </div>
    <div id="noisy">
        <p><a href="http://www.youtube.com/watch?v=eHnnGHgeyC0">Noisy fruit and veggies - Synesthesia</a></p>
    </div>
    <div id="watermelon">
        <p><a href="http://www.bbc.co.uk/news/world-asia-pacific-13421374">China farmers face 'exploding' watermelon problem</a></p>
    </div>
    <script>
    var tabs = document.getElementById('tabs');
    tabs.onclick = function (evt) {
        evt = evt || window.event;
        var link = evt.target || evt.srcElement,
            links,
            i,
            target;
        if (link.nodeType === 1 && link.nodeName === 'A') {
            links = this.getElementsByTagName('a');
            for (i = 0; i < links.length; i += 1) {
                target = document.getElementById(links[i].href.split('#')[1]);
                if (link !== links[i]) {
                    target.className = 'hidden';
                } else {
                    target.className = '';
                }
            }
            return false;
        }
    };
    </script>
    </body>
    </html>
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  7. #7
    SitePoint Zealot
    Join Date
    Oct 2010
    Posts
    167
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Paul,

    Thanks for sharing this link with me.

    It is very useful information to have. Although, I need something very similar but not quite the same as this. Would you be so kind as to advise how to adjust this code.

    Your code above shows all of the DIVs until you click one of them and then hides all except for the one you click. What I need is to automatically load one of the DIVs on page load (hiding the rest) and then switch to one of the others when clicked.

    So using your code as an example, I would want Apple to be shown on page load and all of the others to be hidden. Then when I clicked on Banana, I would want to hide Apple along with the others and display just Banana. I would also want to style the Active link with a different colour so the user knows which one is already being displayed. So on page load, the Apple link would be red and then when I clicked on Banana, this style would switch to that link.

    How would I achieve this?

  8. #8
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,527
    Mentioned
    84 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by CBResources View Post
    So using your code as an example, I would want Apple to be shown on page load and all of the others to be hidden. Then when I clicked on Banana, I would want to hide Apple along with the others and display just Banana.
    You would achieve it after setting up the onclick event, by having the script click the first link.

    Code javascript:
    tabs.getElementsByTagName('a')[0].click();
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  9. #9
    SitePoint Zealot
    Join Date
    Oct 2010
    Posts
    167
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for your reply Paul.

    I'm not as experience with Javascript as some - where in the code do I put that extra line?

  10. #10
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,527
    Mentioned
    84 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by CBResources View Post
    where in the code do I put that extra line?
    At the bottom of the script.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  11. #11
    SitePoint Zealot samg914's Avatar
    Join Date
    Nov 2009
    Location
    Boston, MA
    Posts
    132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks guys!


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
  •