Bootstrap: How to fade and then hide something using the default 'fade', 'hide', 'in' classes?

davidpauljunior picture davidpauljunior · May 30, 2013 · Viewed 90.1k times · Source

Bootstrap obviously makes use of the 'hide', 'fade' and 'in' classes for its transitions.

The problem I'm having is that using 'fade' and 'in' will change the opacity from 0 to 1. The transition effect is perfect, but the content is still there taking up space on the page, even if you can't see it. For example, if it's container has a border, there'll be a big white space before the border.

I want to make use of their exisiting CSS transitions by adding and removing the 'in' class, but I also want whatever element that's fading out, to be hidden, but only after the transition is over. So basically, exactly what they do in the modal, but I don't know how they do it.

In my example below, adding or remove the hide means the div appears or disappears instantly, before the fade effect can happen.

JS fiddle here

Example HTML:

<div class="control-group">
    <label class="control-label">Choose one:</label>
    <div class="controls">
        <label class="radio inline">
            <input type="radio" name="color-radio" id="yellow-trigger" value="yellow" />Yellow Box</label>
        <label class="radio inline">
            <input type="radio" name="color-radio" id="red-trigger" value="red" />Red Box</label>
    </div>
</div>
<div id="yellow-box" class="hide fade">
    <p>I'm yellow</p>
</div>
<div id="red-box" class="hide fade">
    <p>I'm red</p>
</div>

Example JS:

$(document).ready(function () {
    $('#yellow-trigger').click(function () {
        $('#yellow-box').addClass('in').removeClass('hide');
        $('#red-box').addClass('hide').removeClass('in');
    });

    $('#red-trigger').click(function () {
        $('#red-box').addClass('in').removeClass('hide');
        $('#yellow-box').addClass('hide').removeClass('in');
    });
});

Answer

Zane picture Zane · May 30, 2013

Any reason not to just use jQuery for the fadeIn effect? Below is some code to make the fade in effect with jQuery.

Fiddle here

Removed "fade" class

<div id="yellow-box" class="hide">
<p>I'm yellow</p> </div>

Updated jQuery for fade in

$(document).ready(function () {

  $('#yellow-trigger').click(function () {
      $('#red-box').hide();
      $('#yellow-box').fadeIn('slow');
  });

  $('#red-trigger').click(function () {
      $('#yellow-box').hide();
      $('#red-box').fadeIn('slow');     
  });

});