(adventures in web programming.)

Recent Entries
Meta (2)
Test (3)
Random (1)
jQuery (1)
SVG (1)

jQuery magicText

-trojal @ 2009-Oct-26 01:07 UTC
So I was taking to learning jQuery, because it was recommended by someone (Nate) and it seemed like a reasonable enough Javascript library for the kinds of things I do with JS.
function spanWords(element){
  var a = $(element).clone().empty();
  $($(element).html().split(" ")).each(function() {
    a.append('<span class="magicText">' + this + '</span> ');
$(document).ready(function() {
  $('.magicText').live('click', function(){
    var a = $($('.magicText').get(Math.floor(Math.random() * $('.magicText').size()))).text();
    if($(this).text().charAt(0) != $(this).text().charAt(0).toLowerCase())
      a = a.charAt(0).toUpperCase() + a.slice(1);
      a = a.toLowerCase();
      a = a.slice(0,a.length-1);
      a += $(this).text().charAt($(this).text().length-1);
  $('.text').each(function() {
This first adventure in jQuery was just a simple script to automatically break any element containing a text node into spans based on word boundaries created by spaces, and adding an onclick event to those spans that would change their text to that of another of the spans.
The important part was to have minimal interference into the structure of the page and still have a nice effect:
<h2 class="text">Lorem Ipsum</h2>
<div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
So I just add the class "text" to the element containing, well, a text node with words in it and the javascript takes care of the rest. Also, as an added bonus, I added the script to the text here.