Julian Camilleri
Julian Camilleri

Reputation: 3095

Width toggle animation - glitchy effect

I'm trying to implement a sliding effect on the text next to the image by using animate and width: toggle once a user clicks on the image (as shown in the jsfiddle below).

The problem I'm encountering is that when it's 'sliding', it glitches between words; my assumption is that it's due to words being moved around in the element.

JSFiddle.

$('img').on('click', function(e) {
  $('span').animate({
    width: 'toggle'
  }, 400)
});
span {
  display: inline-block;
  max-height: 20px;
  width: auto;
  position: absolute;
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://via.placeholder.com/50x50" alt="">
<span>Name Surname</span>

Is there a way to fix the glitchy effect?

Upvotes: 2

Views: 182

Answers (2)

Arun Sharma
Arun Sharma

Reputation: 1331

The easiest way to fix this is by preventing text wrap by setting white-space: nowrap in your CSS code.

$('img').on('click', function(e) {
  $('span').animate({
    width: 'toggle'
  }, 1200)
});
span {
  display: inline-block;
  max-height: 20px;
  width: auto;
  white-space: nowrap;
  position: absolute;
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img src="http://via.placeholder.com/50x50" alt="">
<span>Name Surname</span>

Upvotes: 3

Shadow Fiend
Shadow Fiend

Reputation: 1829

Try this.

$('img').on('click', function(e) {
	$('span').animate({width: 'toggle'}, 400);
});
span {
  display: inline-block;
  max-height: 20px;
  width: auto;
  position: absolute;
  overflow: hidden;
}
   <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<img src="http://via.placeholder.com/50x50" alt="">
<span>Name&nbsp;Surname</span>
Here is the Updated Fiddle.

Upvotes: 4

Related Questions