tags:

views:

166

answers:

2

how can i use jQuery to show/hide the same div area... essentially swapping out content?

here is what i have so far, and i cant figure out how to hide the previous content and replace it with the new content:

       <script type="text/javascript">
    $(document).ready(function(){

    $('.content').hide();

    $('a').click(function(){
    $('.content').show('slow');
    });

    //then hide previous content

    });

    </script>

<a href="#" id="a-link">A</a>
<a href="#" id="b-link">B</a>

  <div class="start-content" id="a">
  content here
  </div>

  <div class="content" id="b">
  content here
  </div>
A: 

Keep the content div visible; instead, just swap out the HTML content with $('.content').html(strvalue);

LesterDove
+1  A: 

If you wrap the contents in a div, this would be a bit easier, like this:

<div id="wrap">
  <div class="start-content" id="a">
  content here
  </div>

  <div class="content" id="b">
  content here
  </div>
</div>

And this in jQuery:

$('a').click(function(){
  $("#wrap > div").hide(); //hide previous
  $('.content').show('slow'); //show what's clicked on
});

Since you have a convention with your IDs though, you can use that, either give you links a class, or wrap them as well, like this:

<div id="links">
  <a href="#" id="a-link">A</a>
  <a href="#" id="b-link">B</a>
</div>
<div id="wrap">
  <div class="start-content" id="a">
  content here
  </div>    
  <div class="content" id="b">
  content here
  </div>
</div>

Then you could use a single event handler for all your links like this:

$('#wap > div:not(.start-content)').hide(); //Initial hide
$("#links a").click(function() {
  $("#wrap > div").hide(); //hide previous
  var id = $(this).attr("id").replace('-link', ''); //matching id
  $('#' + id).show('slow'); //show what's clicked on
});
Nick Craver
Great. Perfect... question though... when the page loads, i can initially see the content for: <div class="content" id="b"> for a split second, then it hides... is that a browser issue? Is there a way to hide it immediatley?
tony noriega
@tony - Give the other divs a css class that's hidden, or add this `#wrap>div { display: none;}` followed by this line `#wrap>div.start-content { display:block; }` to your CSS, this will initially hide them, and you can remove this line from the script: `$('#wap > div:not(.start-content)').hide();`
Nick Craver