0

I am using following code to explode the value in text. I separated textbox string separate char, but while i am exploding the whole div get exploded. Help me

var explode=$("#text").val();
var len=explode.length;
var text="";
for(var i = 0;i < len; i++)
{
    var res=explode.charAt(i);
    $("#div").append("<span id="+i+" >"+res+"</span>");
}
for(var j=0; j < len; j++)
{
    $("#"+j).each(function(i){
        $("#"+j).css('position','relative');
        $("#"+j).animate({left:'250px',opacity:'0.5',top:'250px',bottom:'500px'});
    });
}
chridam
  • 100,957
  • 23
  • 236
  • 235
jerome
  • 31
  • 6

1 Answers1

1

As I understand the term, "explode," you want characters to go flying in various directions. If I correctly understand your desire, then as I stated in my comment, the main problem is that you're running the same animation on each char span at practically the same time. You need to randomly choose some values to which you'll animate for each separate char span.

Here is some code which should be a little more efficient for you, and which uses random values for the animations:

var explode = $('#explode_text').val(),
    container = $('#explode_container'),
    getRandomInt,
    len = explode.length,
    i;

/*
 * From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
 */
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

for (i = 0; i < len; i += 1) {
    container.append(
        $('<span />').text(explode.charAt(i))
    );
}

container.children('span').each(function () {
    $(this)
        .css('position','relative')
        .animate({
            opacity: '0.5',
            left: getRandomInt(0, 250) +'px',
            top: getRandomInt(0, 250) +'px',
            bottom: getRandomInt(0, 500) +'px'
        });
});

JSFiddle demo: http://jsfiddle.net/M8EP8/1/

JAAulde
  • 19,250
  • 5
  • 52
  • 63
  • ,But i can not understand abour math.floor,math.random function. Could u pls explain what happens? – jerome Jun 21 '14 at 03:07
  • JavaScript's `Math.random()` is a little odd in that it returns a decimal between 0 and 1. By manipulating that return with the min and max the way we do, and by rounding it down to a whole number, we get a workable value in the range we desired. – JAAulde Jun 21 '14 at 03:13