Nov 16, 2009

How to write your own jquery plugins – random size plugin

Let’s continue our plugin example. I’ll change the plugin from the first post to something a little more fun.

RandomSize plugin – it will change the font size of all inner html elements with random values. For this goal we need a list of 'this' element children.

var c = $(this).children();

We can generate random numbers with the expression:

Math.floor(Math.random() * max)

where max is our max value. Also it is better to have a min value because people can’t read font with size 1. So our expression will evolve this way:

Math.floor(min + Math.random() * (max - min))

Here is the plugin code:
(function($) { 
$.fn.randomSize = function(settings) {
    var config = { 
  'fontWeight' : 'bolder'};
     if (settings) 
      $.extend(config, settings);
     this.each(function() {
  var c = $(this).children();
  c.each(function() {
   var rand = Math.floor(
    parseInt(config.min) + 
    (Math.random() * 
    (config.max - config.min)));
   var cssObj = { 
       'font-size':rand + 'px', 
     return this;

Sample html:
 <span>Element 1</span>
 <span>Element 2</span>
 <span>Element 3</span>

And we call it like this:

No comments:

Popular Posts