Hide several divs, show 1 by default, and switch (show/hide) between them based on link click?

I know the show/hide thing has been covered to death on stack, but I just can't find a solution that works for me, sorry. I've tried several JS/jQuery solutions that I found and can't quite get one to behave the way I'd like.

I have many divs that are very similar in content (content changes slightly based on version selected), and all have the exact same style.

Desired behavior

I'd like one div to show by default with all others hidden. Then, based on a link click, a different version div is displayed and all other content divs are hidden.

Basic HTML

<div class="container">
  <p>Basic info about page</p>
    <li><a href="#ver1" id="linkToVer1">Version 1</a></li>
    <li><a href="#ver2" id="linkToVer2">Version 2</a></li>
    // More links to other divs

  <div class="content" id="ver1">    // I'd like this div to be the default
     Content here                    // when the page loads. All other divs 
  </div>                             // are hidden until a link is clicked.

  <div class="content" id="ver2">
     Content here

  // More content divs

I'll have up to a dozen different versions of these content divs.

JS or jQuery is fine, but jQuery is preferred because I'll probably add some kind of show/hide effect. I don't care that greatly about the naming structure of the divs or links.


$("div.containter ul li").each(function(){


      $("div" + $(this).attr("href")).show();


Wrap that in a $(document).ready or whereever and you should be good to go my friend. Learn the code, so that in the future, you are gosu.


How about adding some more RESTful behaviour.

   // get the location hash
   var hash = window.location.hash;
   // hide all
      // show the div if hash exist
      // show default 
   $("div.containter ul li a").click(function(){
      // hide all

I suggest you to use on() jquery function with selector. And also you can show the default div using css. Here is the complete code.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.