Search code examples
jqueryhtmlshow-hide

jQuery Show/hide multiple div using buttons


Sorry for asking a very basic question and I am very new to jQuery. I have a following piece of HTML

<!DOCTYPE html>
<html>
<head>
    <title>Test Div</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
</head>
<body>
    <nav> 
    <div id='menu'> 
    <img src='img/Navigation/home.png' title='Home' alt='' /> 
    <img src='img/Navigation/info.png' id="aboutUs" title='About Us' alt='' /> 
    <img src='img/Navigation/gallery.png' id="portfolio" title='Portfolio' alt='' /> 
    <img src='img/Navigation/facebook.png' title='Follow us' alt='' /> 
    <img src='img/Navigation/contact.png' id="contactUs" title='Contact Us' alt='' /> </div>
  </nav>
  <div style="clear:both"></div>
  <div id="contactUs" style="height:300px; width:300px; background-color:#999; display:none;">Contact Us</div>
  <div id="portfolio" style="height:300px; width:300px; background-color:#999; display:none;">Portfolio</div>
  <div id="aboutUs" style="height:300px; width:300px; background-color:#999; display:none;">About Us</div>
</body>
</html>

I want to show contactUs, portfolio and aboutUs Divs to be displayed on clicking corresponding buttons.

I searched for tons of examples online still can't make it work.


Solution

  • $("#content > div").hide();
    
    $("#menu a").click(function(){
        $("div#" + $(this).attr("id")).show();
    });
    

    You have a problem with using the same id for your img tags and your div tags

    Try something like this:

    <body>
        <nav> 
            <div id='menu'> 
                <a><img src='img/Navigation/home.png' title='Home' alt='' /> 
                <a href="#contactUs"><img /></a>
                <a href="#portfolio"><img /></a>
            </div>
        </nav>
        <div style="clear:both"></div>
        <div id="content">
            <div id="contactUs">Contact Us</div>
            <div id="portfolio">Portfolio</div>
            <div id="aboutUs">About Us</div>
        </div>
    </body>
    

    $("#content > div").hide();
    
    $("#menu a[href]").click(function(){
        $("#content " + $(this).attr("href")).show().siblings().hide();
    });