Cambiar texto con jquery, no puedo hacer las transiciones correctamente

I am working on a text effect but the transition is not completely to my liking.

I am replacing a single word in a line of centered text, I make the old word fade out and the new one fade in, but the surrounding text "jumps". I have been trying for a while to figure out how to make it slide to it's new spot somehow by using an animation on margins or width, but I cannot seem to figure it out.

Here is a JSfiddle of what I have right now http://jsfiddle.net/DEk7m/3/

What I am trying to achieve is something similar to what is seen in the big title here: https://gumroad.com/

Y aquí está el código:

HTML:

<h1 id="changingtext">This is <span>changing</span> text</h1>

CSS:

h1 {
text-align: center;
font-family: helvetica, arial, sans-serif;
}

JavaScript (usando jQuery):

$(function() {
  var t1 = new Array("changing", "dynamic", "cool");
  var i = 0;
  var tid = setInterval(
      function() {
        $("#changingtext span").animate({'opacity': 0}, 1000, function () {
            $(this).text(t1[i]);
        }).animate({'opacity': 1}, 1000);

        if(i < t1.length -1) 
            i++;
        else i = 0;

      }, 3000 );

});

muchas gracias!

preguntado el 05 de mayo de 13 a las 14:05

The simplest thing to do would be to fix the width of the <span>. Anything beyond that is going to be pretty hard, because the browser doesn't give you much control over how the inline layout mechanism works. -

... and you could animate the width of the span too; that'd probably help. -

I added a link to something similar that I am trying to achieve, see the big title here: gumroad.com -

4 Respuestas

Width is missing in your demo, Have a look at this,

HTML

<body>
    <h1><span id="chkWidth" style="display: none;"></span></h1>
    <h1 id="changingtext">This is <span>changing</span> text</h1>
</body>

Guión

$(function() {
  var t1 = new Array("changing", "dynamic", "cool");
  var i = 0;
  var width;
  var tid = setInterval(
      function() {
          $("#changingtext span").animate({'opacity': 0}, 1000, function () {
            $(this).text(t1[i]);
            width = $('#chkWidth').text(t1[i]).width();
            $(this).animate({'opacity': 1, 'width': width}, 1000);
        });

        if(i < t1.length -1) 
            i++;
        else i = 0;

      }, 3000 );

});

http://jsfiddle.net/DEk7m/8/

Espero que esto te ayudará.

contestado el 05 de mayo de 13 a las 15:05

Better idea than mine +1 :) - hitautodestruct

SEE ANOTHER ANSWER COVERING THE SAME QUESTION

BON! No need for setInterval when you deal with .animate()
An even better approach without the first change gap/jump
and with dynamically calculated span anchos:

DEMO EN VIVO

CSS:

h1 span{
    /* To prevent a jumpy misaligned SPAN due to widths change. */
    vertical-align:top; 
}

jQ:

$(function() {

  var t=["changing", "dynamic", "cool"],
      $h1 = $("#changingtext"),
      $sp = $h1.find("span"),
      i=0,
      widths=[];

  $.each(t, function(i, v){
      var el = $('<span />', {text:v}).appendTo($h1);
      widths.push(el.width());
      el.remove();
  });

  $sp.css({opacity:0});

  (function loop(){
     i = ++i%t.length;    
     $sp.text(t[i]).animate({width:widths[i]}, 1000, function(){
       $(this).animate({opacity:1},1000).delay(3000).animate({opacity: 0}, 1000, loop); 
      });     
  })(); 

});

This code group

  $.each(t, function(i, v){
      var el = $('<span />', {text:v}).appendTo($h1);
      widths.push(el.width());
      el.remove();
  });

stores inside our widths[] array all the needed widths we need.
We'll treat the widths[] iterations same as you already do for t[]

than we create a recursive self-invoking function (no hay necesidad de setInterval !) where we'll test for i convertirse 0 usando un simple Modulo Operator (Reminder) %

i = ++i%t.length;

The function "looping" is simply achieved recalling that function inside the last chained animation callback.

contestado el 23 de mayo de 17 a las 13:05

nice, but while expanding its a little buggy. - Shlomi Hasid

@ShlomiHassid haha ok thanks, just moved the width animation inside the first animation callback :) Do you like it now? - Roko C. Bulján

sorry for the poor english - Shlomi Hasid

@ShlomiHassid I got it, edited and added the demo, take a look! - Roko C. Bulján

Animate opacity y anchura

You can set up an object array to include the ideal width for each instance that comes next.

var t1 = [ ['changing', '130px'], ['dynamic', '80px'], ['cool','150px'] ],
    i = 0;

var tid = setInterval( function() {

  $("#changingtext span")
  .animate({
    'opacity': 0,
    'width': t1[i][1] },
    500,
    function() {
      $(this).text( t1[i][0] );
    })
  .animate({'opacity': 1}, 1000);

  if(i < t1.length -1) 
    i++;
  else
    i = 0;

}, 3000 );

Demostración en JSFiddle.

This is a bit of a static and cumbersome way but it should set you off on the right direction.

You could probably figure out the sizes of the spans dynamically by printing the words as a span list, measuring their width and adding their widths to the array.

contestado el 05 de mayo de 13 a las 15:05

Ok here is a working example i quickly made for you: violín

As you can see I am using another element that is hidden and contains the next string for calculating the correct width - all u need now is just

 Fading out >>> Animating the width >>> Text >>> Fade in.

The text is not jumping while fading out because the outer words are floated to the left/right.

Divertirse....

jquery:

var words1 = new Array(  "dynamic", "changing", "cool");
var i1 = 0;
$("#next1").text($("#outer1").text()).hide();
$("#outer1").width($("#next1").width());

 var tid1 = setInterval(
 function() { 
     var word_in1;
     if (typeof  words1[i1+1] !='undefined') { word_in1 = words1[i1+1] } else { word_in1 =
    words1[0]; }
    var by_char_next1 = $("#next1").text('This is '+ word_in1 + ' text').width();
     $("#changingtext1").fadeOut(1000, function(){
         $("#outer1").animate({'width': by_char_next1 },1000,function(){
         $("#changingtext1").text(words1[i1]).fadeIn(1000);
         });
     });
    if (i1 < words1.length-1) i1++;
    else i1 = 0;
   }, 3000 );

CSS:

  #outer1,
  #changingtext1
 {
 padding:0;
 margin:0;
 font-size: 40px;
 font-weight: bold;
 font-family: helvetica, arial, sans-serif;
}
#next1{
padding:0;
margin:0;
  font-size: 40px;
 font-weight: bold;
font-family: helvetica, arial, sans-serif;  
}

HTML:

<center>
<div id='outer1' align='center'>
    <span style='float:left;'>This is</span>
    <span id="changingtext1">changing</span>
    <span style='float:right;'>text</span>
</div>
<br />
<span id='next1'></span>
</center>

contestado el 05 de mayo de 13 a las 17:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.