2

I've decided to update all my jquery to work with jquery 1.9.1 but I can find out why this script has stopped working. Works fine in all other jquery versions.

// Typewriter function
$.fn.Typewriter = function Typewriter(opts) {
    var $this = this,
        defaults = {
            animDelay: 50
        },
        settings = $.extend(defaults, opts);
    var objDiv = document.getElementById(settings.div);
    $.each(settings.text, function (i, letter) {
        setTimeout(function () {
            $this.html($this.html() + (letter != '\n' ? letter : '<br />'));

            objDiv.scrollTop = objDiv.scrollHeight;
        }, settings.animDelay * i);
    });
};

// Call with 
// $('#divID').Typewriter({animDelay: 10,text: 'text to animate', div: 'divID'});

$('#outputDiv').Typewriter({
    animDelay: 10,
    text: 'Why does this not work in jquery 1.9.1? :( ',
    div: 'outputDiv'
});

Js fiddle included below

http://jsfiddle.net/T2AJ5/

EDIT:

Using the chrome development tool I get a error in the console reading:

Uncaught TypeError: Cannot use 'in' operator to search for '42' in Why does this not work in jquery 1.9.1? :(

JAAulde
  • 19,250
  • 5
  • 52
  • 63
Dan Wilkins
  • 100
  • 7
  • Please elaborate on "stopped working". Is there an error? Does nothing happen? Does your computer catch on fire? – jbabey Feb 25 '13 at 19:34
  • Nothing happens, calling the function doesn't output anything to outputDiv – Dan Wilkins Feb 25 '13 at 19:36
  • 1
    Are you passing a string to `$.each`? – Ian Feb 25 '13 at 19:41
  • 6
    It's failing because you passed text into $.each rather than an object or an array. If you use methods the way they are documented, you won't run into as many issues on upgrades to the library. Split the string before passing it into $.each. – Kevin B Feb 25 '13 at 19:41
  • 2
    @KevinB sounds like an answer; I can confirm the behavior that `each` use to work on strings and 1.9 broke it. – vcsjones Feb 25 '13 at 19:42
  • Yeah, try this http://jsfiddle.net/TmLrC/ with different versions of jQuery set - it seemed to work pre-1.9 – Ian Feb 25 '13 at 19:43
  • Yep, definitely changed in 1.9. Same problem was raised, but classified as not a bug by JQ: http://bugs.jquery.com/ticket/13362. – Simon C Feb 25 '13 at 20:34

1 Answers1

6

One does not use $.each to loop over strings. I doubt it worked properly before. For a quick fix, change it to settings.text.split('').

Btw, appending to innerHTML can be troublesome. Better use the DOM, see here for that callback hell wrapped in a jQuery plugin :-)

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375