3

A helpful SO answer taught me how to toggle an element by sliding it horizontally instead of vertically.

$('div').animate({ width: 'toggle' });

However, a new problem arises when text is in the element - the animated width introduces word wrap and other sensitive elements react poorly.

When animating, the height of it jumps all over the place and the effect is quite unpleasant. This snippet fully demonstrates the problem:

$('a').click(function() {
  $('div').animate({
    width: 'toggle'
  });
});
div {
  background-color: red;
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>a b c d e f g h</div>
<a href="#">test</a>

I would like to see it like a static image - if the word wrap makes two lines, it should stay as two lines as it animates. Everything else is already cool and dandy.

http://jsfiddle.net/tdbhmcaz/

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Scar
  • 148
  • 9

1 Answers1

1

The issue is because changing the width of the element as it animates causes the text to overflow.

To fix this you can instead use a containing div set to overflow: hidden, and then animate the left property of an inner div, something like in the example below.

$('a').click(function() {
  $('.content').animate({
    left: $('.content').css('left') === '0px' ? '-100px' : '0px'
  });
});
.container {
  position: relative;
  overflow: hidden;
  height: 20px;
  width: 100px;
}

.content {
  position: absolute;
  height: 100%;
  width: 100%;
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="content">
    a b c d e f g h
  </div>
</div>

<a href="#">test</a>

Also note that jQuery 1.9.1 is rather outdated. I'd suggest updating it.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339