EasyBB
EasyBB

Reputation: 6544

Vanilla JavaScript with Function, function not defined

$(function() {
 var script = document.createElement('script');
 script.id="filepicker";
 script.type="text/javascript";
 script.src="//api.filepicker.io/v1/filepicker.js";
 var body=document.querySelectorAll("body")[0]; ;
 body.appendChild(script);
 var ButtonsArea = document.querySelectorAll('.frm-buttons')[0];
 var textArea = document.getElementById('text_editor_textarea');
 var button = document.createElement('span');
 var divText=document.createTextNode("Upload File");
 button.id="newDoc";
 button.setAttribute("onclick","getPick()");
 button.appendChild(divText);
 ButtonsArea.appendChild(button);

  function getPick(){
   filepicker.setKey('AWpNcAmH9TmiWtEgHsFwBz');
   filepicker.pick({
    mimetypes: ['text/*'],
    services:['COMPUTER'],
    maxSize:50*1024
   },function(FPFile) {
     var docFile = FPFile.url;
     textArea.value=textArea.value+'[url]'+FPFile.url+'+'+FPFile.filename+'[/url]';
     });
  }
});

my getPick() function is being said it is not defined is there something that I am missing from all of the JavaScript, maybe the JavaScript timing is off since everything is being created dynamically?

Upvotes: 1

Views: 2085

Answers (2)

lonesomeday
lonesomeday

Reputation: 237817

The problem is that when you declare a function within the scope of another function, it is limited to the scope of that function. When you call getPick() on the element's onclick attribute, it is executed in the global scope. getPick doesn't exist there.

You can instead simply assign the function as the onclick property:

button.onclick = getPick;

You can increase the flexibility of your code by using addEventListener, which would look like this:

button.addEventListener('click', getPick, false);

This allows you to have more than one click handler on the button if you should so choose, but it isn't compatible with old versions of Internet Explorer. button.onclick = is compatible with almost all browsers going back a very long way into Internet history!

Note that in both those cases you are using getPick rather than getPick(). The former is a reference to the function; the latter executes the function and gives you its return value.

Upvotes: 2

jcsanyi
jcsanyi

Reputation: 8174

The getPick() function is defined locally inside the anonymous on-ready function, so it's not visible to the onclick handler.

Try moving the getPick function outside the $(function() { }); block.

Alternatively, use proper event handling, something like the following:

button.click(function() {
    filepicker.setKey('AWpNcAmH9TmiWtEgHsFwBz');
    filepicker.pick({
        mimetypes: ['text/*'],
        services:['COMPUTER'],
        maxSize:50*1024
    }, function(FPFile) {
        var docFile = FPFile.url;
        textArea.value=textArea.value+'[url]'+FPFile.url+'+'+FPFile.filename+'[/url]';
    });
});

Upvotes: 1

Related Questions