2

I am using another Stackoverflow post's JavaScript example to rotate the text of a span that sits inside of an h3. I don't understand why the text that is significantly longer, but is a single word, stays on one line, but the text that is much shorter but has two words goes to two lines?

var arr = ['signficantly_longtext_than_others', 'Data Science', 'Front-End Development', 'Programming', 'Product Management', 'Digital Marketing', 'Mobile Development', 'Web Design'],
    i = 0, // Start Index
    len = arr.length,
    $el = $('.rotate span'),
    $temp = $('<span />'); // Helper - Will measure Text width
    console.log($temp)
$temp.hide().appendTo( $el.parent() ); // Setup Helper

(function loop() {
  console.log(arr[i%=len])
  var w = $temp.text( arr[i%=len] ).width(); // set text + get width
  console.log(w);
  $el.fadeTo(600,0).animate({width: w}, 600, function(){
    $(this).text( arr[i++] ).fadeTo(600, 1);
  });
  setTimeout(loop, 3000);
}());

View it live: http://codepen.io/maudulus/pen/RWRMwj

Community
  • 1
  • 1
maudulus
  • 10,627
  • 10
  • 78
  • 117

2 Answers2

1

To address the issue, you can add white-space: nowrap;

h3 {
  padding-top:20px;
  margin-top:0;
  font-weight: 800;  
  font-size: 26px; 
  white-space: nowrap;
}

http://codepen.io/anon/pen/RWRMVy

Jack
  • 9,151
  • 2
  • 32
  • 44
  • any idea how you can stop the whole thing from bumping down for a second before the transition? – maudulus Sep 21 '15 at 21:06
  • It seems to be an issue with the `animate` call. A quick fix seems to be removing the element from flow so it doesn't affect layout (like: http://codepen.io/anon/pen/ojLqdE) - One thing I'm curious though is why you need to calculate the width? – Jack Sep 21 '15 at 21:30
0

That happens because of containers width.

Change CSS to something like this:

h3 {
  padding-top:20px;
  margin-top:0;
  font-weight: 800;  
  font-size: 26px; 
  width: 7000px;
}
span { 
  width: 6000px;
}

Demo: http://codepen.io/anon/pen/vNKRgd

(Of course numbers like 6000px and 7000px taken haphazardly. Put there something that suits you.)

Shultc
  • 214
  • 1
  • 12