Proto.TextResizeDetection – Prototype Text Resize Detection

This is inherited from the techniques used in A List Apart – Text-Resize Detection. When I wrote this class and wanted to write about it, Mislav created another Prototype based text resize script. However, I’m still going to write about it :) .

The idea behind detecting text resizing is quite simple. It consists of creating a hidden span and periodically checking the current height of the span.

Let’s start by initializing the Proto.TextResizeDetection:

if (typeof Proto == 'undefined') var Proto = {};
 
Proto.TextResizeDetection = Class.create({
  initialize: function(time)
  {
    this.time = (time / 1000);
    this.size = 0;
    this._createSpan();
    this.start();
  },
 
  ...
});

The constructor takes only one argument, time. This is the interval, in milliseconds, we use to check the dimensions of the span to see if the text has resized.

In our constructor we build our span and then start the PeriodicalExecuter:

  _createSpan: function()
  {
    this.el =
      new Element('span', {id: '_text_resize_detection_span'})
      .setStyle({
        position: 'absolute',
        top: '-9999px',
        left: '-9999px'
      })
      .update(' ');
 
    $(document.body).insert({top: this.el});
  },

This method creates a span with it’s position being absolute and hides it way beyond the upper left corner. We then insert this at the top of the document.body

After the span is created, we will now start to periodically check the dimensions of the span. This allows us to determine if the text size has indeed changed.

  start: function()
  {
    this.size = this.el.offsetHeight;
    this.pe = new PeriodicalExecuter(this._onTextResize.bind(this), this.time);
  },

For every X amount of seconds, the PeriodicalExecuter will call the _onTextResize method:

  _onTextResize: function()
  {
    var currentSize = this.el.offsetHeight;
    if (this.size != currentSize)
    {
      document.fire('text:resized', {
        previousSize: this.size,
        currentSize: currentSize
      });
      this.size = currentSize;
    }
  }

This method simply compares the previous size of the span with the current size and if they are different, we will fire a custom event, document.fire('text:resized') with the previous and current offset height of the span.

To see when the text size has changed, you can simply observe the text:resized event on the document:

  new Proto.TextResizeDetection(1000);
  document.observe('text:resized', function(e) {
    alert('Text size has changed! Current size: ' + e.memo.currentSize + ' - Previous size: ' + e.memo.previousSize);
  });

Click here to view a live demonstration.

You can view/download the script in it’s entirety here.

0 Response to “Proto.TextResizeDetection – Prototype Text Resize Detection”


  • No Comments

Leave a Reply