Search code examples
javascriptjquerypluginschaining

Allow chaining in jQuery plugin


it's been a long day and I can't seem to figure out why one of my custom jQuery plugins won't chain.

What i'm trying to do is write a line of characters out one at a time in an element then when done remove the text then write the next line

The plugin:

(function($) {
  $.fn.writeDialogue = function(content) {
    var contentArray = content.split(""),
      current = 0,
      elem = this,
      write = setInterval(function() {
        if(current < contentArray.length) {
            elem.text(elem.text() + contentArray[current++]);
        } else {
          clearInterval(write);
          return this;
        }
      }, 100);
  };
})(jQuery);

Pretty much i'm trying to chain it in this way:

$('#element').writeDialogue(textLine1).empty().writeDialogue(textLine2);

Can't get it to work, any ideas?


Solution

  • This is because your code is async. so you have to move return this:

    (function($) {
      $.fn.writeDialogue = function(content) {
        var contentArray = content.split(""),
          current = 0,
          elem = this,
          write = setInterval(function() {
            if(current < contentArray.length) {
                elem.text(elem.text() + contentArray[current++]);
            } else {
              clearInterval(write);
            }
          }, 100);
          return this; // THERE
      };
    })(jQuery);