Nermina Avdić Nermina Avdić - 2 months ago 9
jQuery Question

Reveal div on link click with slide animation

Im trying to accomplish displaying different content when clicked on a different section, im using this code:

<style>
.content1 {display:none;}
.content2 {display:none;}
.content3 {display:none;}
</style>


<ul class="sidebar">
<a href=".content1"><li>Link1</li></a>
<a href=".content2"><li>Link2</li></a>
<a href=".content3"><li>Link 3</li></a>
</ul>
<div class="content1 toggle"></div>
<div class="content2 toggle"></div>
<div class="content3 toggle"></div>


Combined with this jQuery:

$(".sidebar a").click(function(e){
e.preventDefault();
$(".toggle").hide();
var toShow = $(this).attr('href');
$(toShow).show();
});


Which works fine, but im trying to do a slide animation, so that once link for .content2 is clicked, .content1 slides up, and .content2 replaces it etc.

Answer

Simply call .slideUp to hide element and .sideDown to show element, read more on the jQuery effect: https://api.jquery.com/category/effects/

JavaScript:

$(".sidebar a").click(function(e){
  e.preventDefault();
  var toShow = $(this).attr('href');

  $(".toggle").slideUp();
  $(toShow).slideDown();
});

CSS

.toggle { width: 100%; height: 100px; }
.content1.toggle { background: #ff0000; }
.content2.toggle { background: #00ff00; }
.content3.toggle { background: #0000ff; }

JSFiddle: https://jsfiddle.net/a827Lmuv/

Bonus

Toggling the active class to control the animation by CSS

JavaScript

$(".sidebar a").click(function(e){
  e.preventDefault();
  var toShow = $(this).attr('href');

  $(".toggle").removeClass("active");
  $(toShow).addClass("active");
});

CSS

.toggle { width: 100%; height: 0; }
.content1.toggle { background: #ff0000; }
.content2.toggle { background: #00ff00; }
.content3.toggle { background: #0000ff; }

.toggle {
  -webkit-transition: .3s;
  transition: .3s;
}
.toggle.active { height: 100px; }

JSFiddle: https://jsfiddle.net/a827Lmuv/1/

Comments