iTux
iTux

Reputation: 53

show hide content from Div, show first by default

I was looking for some code to show / hide divs according to item selected from the menu. I found this code, but only works having all divs hidden from start. Could somebody help to modify it to show first option by default?

Here is the fiddle I found http://jsfiddle.net/dangoodspeed/M3ZhV/

I have tried to toggle the view, but it not working :)

var curPage="";
$("#menu a").click(function() {
    if (curPage.length) { 
        $("#"+curPage).toggle();
    }
    curPage=$(this).data("page");
    $("#"+curPage).toggle();
});

Thanks

Upvotes: 0

Views: 74

Answers (3)

Mohammad Al Baghdadi
Mohammad Al Baghdadi

Reputation: 377

use this

$(function() {

$("a[data-page^='page'").click(function() {
$("div[id^='page']").hide();
	var page=$(this).attr('data-page');
	$("div[id='"+page+"']").show();
});
});
    .content { display:none;}
    .content:nth-child(1)
    {
      display:block;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

    <div class="nav">
        <ul id="menu">
            <li id="link1"><a href="#" data-page="page1">Topic One</a>
            </li>
            <li id="link2"><a href="#" data-page="page2">Topic Two</a>
            </li>
            <li id="link3"><a href="#" data-page="page3">Topic Three</a>
            </li>
        </ul>
    </div>
    <div class="main">
        <div id="page1" class="content">
             <h1>Show Page1</h1>

        </div>
        <div id="page2" class="content">
             <h1>Show Page2</h1>

        </div>
        <div id="page3" class="content">
             <h1>Show Page3</h1>
        </div>
    </div>

Upvotes: 1

sideroxylon
sideroxylon

Reputation: 4416

A slight revision of your current code:

$(function() {
$('#page1').show();
var curPage="page1";
  $("#menu a").click(function() {
     if (curPage.length) { 
         $("#"+curPage).hide();
     }
     curPage=$(this).data("page");
     $("#"+curPage).show();
  });
});

FIDDLE

Upvotes: 1

Kalob Porter
Kalob Porter

Reputation: 440

If you want the first option to show by default, add this to the top (where curPage is)

var curPage="";

if(!curPage){
    $('#page1').show()
  curPage = "page1"
}

Upvotes: 1

Related Questions