Search code examples
javascriptjqueryjsfiddle

JSFiddle doesn't work even if I copy code from another working fiddle


I visited this link to get some help in learning how to play around with Javascript: http://jsfiddle.net/8ZtqL/1/

I attempted it on my project. Didn't work. Hmm. So I made a new JS Fiddle and copied to code over. Still didn't work.. Why? Here's my fiddle which doesn't work: https://jsfiddle.net/mt6bwry9/

The code is an exact copy.

Here's the code used:

var text="This text will be written one by one.";
var delay=200;
var elem = $("#myText");
//text- string
//elem - jQuery element where text is to be attached
//delay - the delay in each text
var addTextByDelay = function(text,elem,delay){
    if(!elem){
        elem = $("body");
    }
    if(!delay){
        delay = 300;
    }
    if(text.length >0){
        //append first character 
        elem.append(text[0]);
        setTimeout(
            function(){
                //Slice text by 1 character and call function again                
                addTextByDelay(text.slice(1),elem,delay);            
             },delay                 
            );
    }
}

addTextByDelay(text,elem,delay);
<body>
    <div id="myText"></div>
</body>


Solution

  • Since you said you're new to JavaScript, here is a little more detailed answer.

    If your JavaScript isn't behaving the way you expect it to, definitely check your browser console. You can do that in Chrome by going to View>>Developer>>JavaScript Console or simply pressing Command+Alt+J. In other browsers you will find similar developer tools.

    In the case of your JS Fiddle, when you open the console you see an error that says $ is not defined. $ is shorthand for jQuery. The JavaScript code that you've copied from the other Fiddle uses jQuery to do DOM Manipulation and your Fiddle hasn't loaded jQuery. So click on the gear icon in your JS section and under Frameworks select jQuery (I recommend 2.2.1) and try running your code again.