KolaCaine
KolaCaine

Reputation: 2187

Animate display block/none, with the comportement of that

So, I will explain clearly, I want to animate a list, when I click on article for example, this hide all other the element and only show all article related on the click

That content replace each other compared at the start that is the comportement of display block/none.

But I can't animate this so if you have a solution I take them !

I don't care about the animation, I want to understand the principle.

Thank

Upvotes: 0

Views: 4630

Answers (2)

voloshin
voloshin

Reputation: 536

Sadly, but an animation between block and none is impossible.

Instead, you can use two steps animation with opacity.

Here's an example with a css bias.

HTML:

...
<div class="block opacity hidden">...</div>
...

CSS (don't forget to add transition):

.block {
  display: block;
  opacity: 1;
}

.block.opacity {
  opacity: 0;
}

.block.hidden {
  display: none;
}

jQuery:

$('.block').removeClass('hidden'); // the block is still invisible
setTimeout( function() {
  $('.block').removeClass('opacity'); // now the block is visible
}, 100); // small delay is needed, better if it's equal the transition time

It's simple. As the alternatives you can use .fadeIn() and .fadeOut() methods or .animate().

UPD

You should remember that timeout in the reverse function have to equals the duration of transition, or the element will be hidden before the end of the animation.

$('.block').addClass('opacity');
setTimeout( function() {
  $('.block').addClass('hidden');
}, 100);

UPD2

JS:

var el = document.getElementsByClassName('block');
el.classList.remove('hidden');
setTimeout( function() {
  el.classList.remove('opacity');
}, 100);

Upvotes: 1

csalmeida
csalmeida

Reputation: 628

You could hide the elements out using jQuery like bdalina suggested and show the only the article that was clicked.

// Hides all articles but the one clicked.
$('article').click(function(){
	$('article').slideUp();
  $(this).slideDown();
});
body {
  font-family: sans-serif;
  background: #003B93;
}

section {
  width: 200px;
  margin: 20px auto;
}

article {
  cursor: pointer;
  margin-bottom: 20px;
  text-align: center;
  background: #BABABA;
  box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
  width: 150px;
  padding: 20px;
  border-radius: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
  <article>First article.</article>
  <article>Second article.</article>
  <article>Third article.</article>
  <article>Fourth article.</article>
  <article>Fifth article.</article>
</section>

Please have a look at this answer as well, it shows another approach to the problem.

Hope this helps in some way.

Upvotes: 3

Related Questions