Wednesday, February 3, 2010

Scrolling page title with JavaScript and jQuery

The following is a jQuery function I wrote that allows you to make a scrolling page title.

I admit...it's a pretty useless "feature" but I just made it to kill some time =D

Usage

The simplest usage is as follows:

$.marqueeTitle();

The above snippet will use your existing title text to scroll.

You can also pass in an object with options to alter the script's behavior. The options are the following:
  • text - Use this parameter to set custom text if you don't want the scrolling text to be taken from the title
  • dir - "left" or "right"; by default, it's set to "left"
  • speed - The time it takes, in ms, for one character rotation

Here's another example, now demonstrating the parameters:

$.marqueeTitle({
  text: "This my custom text",
  dir: "right",
  speed: 500
});

Source

(function ($) {
    var shift = {
        "left": function (a) {
            a.push(a.shift());
        },
        "right": function (a) {
            a.unshift(a.pop());
        }
    };
    $.marqueeTitle = function (options) {
        var opts = $.extend({},
        {
            text: "",
            dir: "left",
            speed: 200
        }, options),
            t = (opts.text || document.title).split("");
        if (!t) {
            return;
        }
        t.push(" ");
        setInterval(function () {
            var f = shift[opts.dir];
            if (f) {
                f(t);
                document.title = t.join("");
            }
        }, opts.speed);
    };
}(jQuery));