user4792749
user4792749

Reputation:

Fix elements jumping around when fading with jQuery

Whenever I fade an element in our out using jQuery, the other elements, being centered vertically, kind of just jump around.

Here's a stripped down example of what I mean:

$("#one").click(function(){
  $("#two").fadeToggle();
});
body {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="one">Paragraph 1</p>
<p id="two">Paragraph 2</p>

When clicking on the first paragraph, the second fades out/in.

What I want to achieve is that instead of well, jumping around, I want it to animate (slide/scroll) between those two positions. How can I do this?

Upvotes: 1

Views: 105

Answers (2)

gaetanoM
gaetanoM

Reputation: 42044

If you can, set the position of first paragraph to relative:

#one {
   position: relative;
}

Then add the animation for the first paragraph:

$('#one').animate({top: animationType + topPos + 'px'});

The snippet:

$("#one").on('click', function() {
    var topPos = Math.ceil($('#one').height());
    var animationType = '+=';
    if ($('#two').is(':not(:visible)')) {
      animationType = '-=';
      topPos = topPos;
    }

    $("#two").fadeToggle();
    $('#one').animate({top: animationType + topPos + 'px'}, 800);
});
body {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}
#one {
    position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<p id="one">Paragraph 1</p>
<p id="two">Paragraph 2</p>

Upvotes: 0

Milan Chheda
Milan Chheda

Reputation: 8249

To avoid jumping, you can use slideToggle():

$("#one").click(function() {
  $("#two").slideToggle();
});
body {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="one">Paragraph 1</p>
<p id="two">Paragraph 2</p>

Upvotes: 1

Related Questions