JSFiddle - React, Tailwind, and code Playground
by prasad raja
HTML
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<div id="bubble"></div>
CSS
body { background-color:#F5F7FA;}
.container { margin:150px auto; width:80%;}
#bubble {
font-size: 25px;
font-family: Comic Sans MS, Verdana, monospace;
color: #222;
font-weight: bold;
}
JavaScript
/*bubbleText({
element: $element, -- mandatory, must be one DOM leaf node
newText: 'new Text', -- mandatory, must be one string
speed: 5000, -- optional, default: 2000
callback: function(){} -- optional
});*/
var bubbleText = function(o) {
var $$, __, bubble;
if (!o | typeof o != 'object' | o.map == [].map) {
throw 'bubbleText() expects an object as argument';
return;
}
if (!(__ = ($$ = $(o.element))[0]) || $$.find(':first').length) {
throw 'bubbleText() expects one DOM leaf in the property "element".';
return;
}
if (typeof o.newText != 'string') {
throw 'bubbleText() expects one string in the property "newText".';
return;
}
// space's width
var span = $('<span data-bubbletext>w w</span>').prependTo($$);
var spaceWidth = span.width();
span.html('w');
spaceWidth -= 2 * span.width();
// height for all spans
var height = span.css('height');
span.remove();
// store properties from each old letter
var oldTable = [];
__.innerHTML = __.innerHTML.replace(/./g, function(x, i) {
oldTable.push({
char: x,
index: i
});
var style = x == ' ' ? ' style="width:' + spaceWidth + 'px"' : '';
return '<span data-bubbletext="old' + i + '"' + style + '>' + x + '</span>';
});
// store properties from each new letter
var newTable = [];
__.innerHTML = o.newText.replace(/./g, function(x, i) {
// index of this letter in the old text
var oldIndex = -1;
for (var i = 0, l = oldTable.length; i < l; i++) {
if (oldTable[i].char == x) {
oldIndex = oldTable[i].index;
oldTable.splice(i, 1);
break;
}
}
// fill this letter's data
newTable.push({
char: x,
index: i,
old: oldIndex
});
return...