ColeGauthier ColeGauthier - 4 months ago 21
jQuery Question

JQuery .replaceWith() or .html()

I am trying to change one div content to another and vice versa when the button is clicked. I would also like to add some animation in between for the separate divs in the content area. I would like for it to switch between both divs. for intsance, showing products for section1 when pressing btn1 and then products for section2 when pressing btn2.

HTML

<button id="btn1" type="button" class="btn">btn1</button>
<button id="btn2" type="button" class="btn">btn2</button>

<div id="section1">
<!-- content goes here -->
</div>
<div id="section2">
<!-- content goes here -->
</div>


JQUERY

$(document).ready(function() {
var section1 = $('#section1')
var section2 = $('#section2')

$('#btn1').click(function() {
$('#section1').html($('#section2').html());
});

$('#btn2').click(function() {
$('#section2').html($('#section1').html());
});
});


Any help would be much appreciated!! :)

Answer

You're better off using show() and hide():

$('#btn1').click(function() {
   $('#section1').show();
   $('#section2').hide();
});

$('#btn2').click(function() {
   $('#section2').show();
   $('#section1').hide();
});

It's easier than messing with the HTML. Also, when you get more advanced at it, you can experiment with various effects, such as fading. Here's a demo of various jQuery effects that you can use with showing and hiding (there are other effects as well, that don't involve showing and hiding).