Cristiano Marques Cristiano Marques - 2 months ago 11
Javascript Question

Uncaught ReferenceError: function is not defined

Im doing a simple jquery function using rangy script but im not being able to get it work, it says the error above.

<div onclick="cmon('cenas');"> cenas </div>

<textarea class="guides_chapters_textarea" id="textarea" name="gmessage" rows="7" cols="25"> Insert starting items here</textarea>


Javascript:

function cmon(text){
$("#textarea").insertText(text, 0, "collapseToEnd");
}


Jsfiddle: http://jsfiddle.net/VmhMM/

Answer

To get your example working, there is a few things you can do. Strictly speaking, there is actually nothing wrong with your code. The fault lies in how your code is being used/added to the page.

Here is one method of getting your code to work, by setting the function on the window object directly.

window.cmon = function cmon(text){
    $("#textarea").insertText(text, 0, "collapseToEnd");
}

Another method mentioned by @elclanrs in the comment on the question (which is a better option in this case) points to the setting in the left panel of the JSFiddle to do with where your function is being run. By default, it adds it to the onLoad event which makes the function out of scope as it is being defined inside the event. Here is exactly what JSFiddle did to your code:

$(window).load(function(){
    function cmon(text){
    $("#textarea").insertText(text, 0, "collapseToEnd");
    }
});

The concept that is going on is known as closures. So when you define a function, any variables or other functions defined inside of that are not accessible externally. If you set the variable on a global object or any other object outside the scope of your newly defined function (like I did in the example I linked), you can access what you defined outside of the closure.