1

I'm writing a javascript function (actually a jQuery prototype) to type some text inside an element. I'm taking this function and wrapping it into a jQuery prototype, like this:

$.fn.typeText = function(text) {
    var txtLen = text.length,
        timeOut,
        char = 0;

    $(this).text('|');

    (function typeIt() {
        var humanize = Math.round(Math.random() * (200 - 30)) + 30;
        timeOut = setTimeout(function() {
            char++;
            var type = text.substring(0, char);
            $(this).text(type + '|');
            typeIt();

            if (char == txtLen) {
                 $(this).text($(this).text().slice(0, -1)); // remove the '|'
                clearTimeout(timeOut);
            }
        }, humanize);
    }());
}

It's giving me this error:

jquery.min.js:3 Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined

My guess is that it can't find the typeIt function on the second timeout call, can someone help me out in this? I want to keep all code for this inside the jQuery prototype function.

Community
  • 1
  • 1
sigmaxf
  • 7,998
  • 15
  • 65
  • 125
  • 1
    Where is the `element` variable defined and what value does it have? – Rory McCrossan Mar 04 '16 at 12:33
  • sorry this was from a previous test, I've updated the question – sigmaxf Mar 04 '16 at 12:39
  • Put a breakpoint and look at the stack looking for your own code – Ruan Mendes Mar 04 '16 at 12:43
  • See how the answer you originally got your function from is using `$el` instead of `$(this)`, the equivalent fix of `var self = this` in one of the answers in the linked duplicate. – James Thorpe Mar 04 '16 at 12:47
  • You could also use fat arrow functions or you could bind (the IIFE and the argument to setTimeout) to `this`. Note that if you were in strict mode, you would have got a different error because functions called without a scope have `this` set to to null instead of the `window` object – Ruan Mendes Mar 04 '16 at 13:00
  • @JuanMendes Indeed - and I think those options are discussed in the duplicate. I mentioned `var self = this` explicitly as it's directly comparable to where the OP got his code from in the first place and it's removing this that's broken it. – James Thorpe Mar 04 '16 at 13:01
  • 1
    @JamesThorpe I know, just summarizing – Ruan Mendes Mar 04 '16 at 13:02
  • @JuanMendes Sounds like we agree :) – James Thorpe Mar 04 '16 at 13:02

0 Answers0