Vertical Text with jQuery
Asked Answered
B

6

8

I'm looking to vertically align text by adding <br /> tags between characters with jQuery.

<div id="foo"><label>Vertical Text</label></div> 

would look like this:

V
e
r
t
i
c
a
l

T
e
x
t

Basir answered 10/11, 2008 at 19:49 Comment(0)
J
26

Let's go golfing!

$('#foo label').html($('#foo label').text().replace(/(.)/g,"$1<br />"));

Completely untested, but the pattern in the regex looks like a boob.

Jugurtha answered 10/11, 2008 at 20:44 Comment(0)
N
4

Mr Kurt's answer works well for a single id, but if you want something more useful that can be applied to several elements try something like this:

$.each( $(".verticalText"), function () { $(this).html($(this).text().replace(/(.)/g, "$1<br />")) } );

Then just set class="verticalText" on the elements you want to be formatted like this.

And as a bonus it keeps the boob regex.

Nickolai answered 9/8, 2010 at 15:16 Comment(0)
S
3

Not tested, but it should work.

var element = $( '#foo label' );
var newData = '';
var data = element.text();
var length = data.length;
var i = 0;

while( i < length )
{

    newData += data.charAt( i ) + '<br />';
    i++;

}

element.html( newData );
Seasick answered 10/11, 2008 at 20:4 Comment(3)
V<br />e<br />r<br />t<br />i<br />c<br />a<br />l<br /> <br />T<br />e<br />x<br />t<br /> is what that makes.Epigeal
That last line needs to be: element.html( newData );Intisar
Indeed. That is better than my answer.Epigeal
C
3

document.write("vertical text".split("").join("<br/>"));

Edit: Hole in one!

Cyanohydrin answered 9/8, 2010 at 15:27 Comment(0)
E
1

This builds on Sebastian H's answer, but I tested it and this works

    var element = $( '#foo label' );
    var newData = '';
    var data = element.text();
    var length = data.length;
    var i = 0;
    $( '#foo label' ).html("");
    while( i < length )
    {
            $( '#foo label' ).append(data.charAt( i ) + "<br />")
            i++;
    }
Epigeal answered 10/11, 2008 at 20:15 Comment(1)
If i have more then one it seems to append to both, thus doubling the text. Any ideas?Basir
B
0

Why use a while loop when you can use jQuery's builtin each method?

$.each( $('#foo').text(), function(){ $('#foo').append(this + '
'); } );

There. It works. You can test it.

Barbarism answered 10/11, 2008 at 22:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.