Access a Function not within the Scope - javascript

I have the javascript code below:
(function($){
function JsBarcode(){
//Some Code Here
}
})(window.jQuery);
(function ($) {
JsBarcode();
//calls a JsBarcode not within a scope
})(jQuery);
When running the code above, it gives the error below:
Uncaught ReferenceError: JsBarcode is not defined
I am trying to call a function, which is not within the scope. How will I be able to call it?

2 options:
- you change the structure so the second module is inside the first: parent scope is always visible.
- you change the first module exporting the function so that you can access it outside. sample below
var firstModuleHandle = (function($){
var JsBarcode = function(){
//Some Code Here
console.log("can access me?");
}
return {JsBarcode: JsBarcode};
})(window.jQuery);
(function ($) {
firstModuleHandle.JsBarcode();
//calls a JsBarcode not within a scope
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

It is because JsBarcode is declared inside a anonymous function, so it is available only inside the limited scope of the anonymous function in which it is declared.
One possible solution is to move the declaration outside of the anonymous function
Another one is to use a global variable to store the reference to the function as given below
//declare it as a gloal variable
var JsBarcode;
(function ($) {
//assign the value of JsBarcode as the function
JsBarcode = function () {
//Some Code Here
}
})(window.jQuery);
(function ($) {
JsBarcode();
//calls a JsBarcode not within a scope
})(jQuery);

If you are not wanting to clutter global namespace can also make it a property of jQuery ... a mini plugin
(function($){
// assign to $ namespace
$.JsBarcode = function (){
//Some Code Here
}
})(window.jQuery);
(function ($) {
// call jQuery.JsBarcode()
$.JsBarcode();
})(jQuery);

Related

Javascript Jquery function undefined error

hi this is my codes in a js page with this name script.js
(function ($) {
myfunc()
{
//some jquery codes
}
}
and I use this function in a html page like this
<html>
<script src='js/script.js'></script>
<button id='btnSent'>sent</button>
<script>
(function ($) {
$('#btns').click(function () {
myfunc();
})
}(jQuery));
</script>
</html>
but in console i have an myfunc is undifined error
myfunc is not global - it's only visible inside of the upper (function ($) { block, due to ordinary Javascript scoping rules. Try using just one (outer) function instead, that way anything else in the inner block would be able to see the myfunc which is also in the inner block:
(function ($) {
function myfunc(){
//some jquery codes
}
$('#btns').click(function () {
myfunc();
})
}(jQuery));
If you have to keep the functionality separate for some reason, you could have script.js assign to a window variable:
(function ($) {
window.myfunc = function() {
//some jquery codes
}
})(jQuery);
You are using IIFEs in both cases. The scope of myfunc() is inside the IIFE in your script.js and not in the global scope.
Hence you cant access it from the IIFE in your html.
Either don't use an IIFE in your script.js just have,
function myfunc(jQuery)
{
//some jquery codes
}
or have the myfunc() inside your IIFE in script tag.
This will be helpful for you to understand better about IIFEs

I can't call a function in js file at html

I have a file, index.php with a tag
<a onclick="listenFilter()" ></a>
and a javascript named test.js linked to my index.php with the function name listenFilter()
$(document).ready(function () {
function listenFilter() {
alert('a');
return false;
}
});
It fails, and my browser says
ReferenceError: listenFilter is not defined
But when I change the script to
function listenFilter() {
alert('a');
return false;
}
It works.
What's different between those two situations?
It is not because the function is defined after the document is loaded. It is because of the scope it is defined in. Script tags in JavaScript automatically bind all variables and function defined in the direct scope of the script tag as global variables (properties of the window object in a browser).
It is because the scope of the function inside the $(document).ready call is unreachable in the global scope, only by other functions in that scope. If you changed it to:
$(document).ready(function () {
window.listenFilter = function listenFilter() {
alert('a');
return false;
}
});
It would work, since you are adding it to the global scope.
$(document).ready(function(){ }) is the same as doing (function(){ })() in the context of this question. Is is a question of scope, not of declaration order. The declaration is being wrapped in a closure which shields it from affecting the global scope.
In the first situation
$(document).ready(function () {
function listenFilter() {
alert('a');
return false;
}
});
You are saying define the function after the DOM is loaded. So at the time the bellow anchor is created, the function listenFilter is not defined.
< a onclick="listenFilter()" ></a>
But in second it will be defined when the anchor is loaded because it's defined while parsing js.
remove this $(document).ready(function () {
<script>
function listenFilter() {
alert('a');
return false;
}
</script>
JavaScript Functions
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed
by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar
signs (same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly
brackets: {}

Calling External function from within function - Javascript

I am using Phonegap and JQueryMobile to create a web application. I'm new to javascript and am having an issue.
My issue is with calling a function I have in a file named "testscript.js", the function is called testFunc. The testscript.js containts only this:
function testFunc() {
console.log("Yes I work");
}
Within my html page I have the following code:
<script>
$('#pageListener').live('pageinit', function(event)
{
testFunc();
});
</script>
The test function is found within my "testscript.js" which I am including with this line within the head tags:
<script src="testscript.js"></script>
The error I get is a "testFunc is not defined".
I am assuming its some type of scope issue as I'm able to call other jquery functions such as:
alert("I work");
and I am able to call my functions by sticking them within script tags in the html elsewhere.
I've tried all sorts of ways of calling my function with no success, any help is appreciated!
You must include the testscript.js before the other jquery code in your html. Like this:
<script src="testscript.js"></script>
<script>
$('#pageListener').live('pageinit', function(event)
{
testFunc();
});
</script>
As long as testscript.js has been loaded by the time PhoneGap fires the pageinit event, and provided the testFunc function is a global, there's no reason that shouldn't work.
You haven't shown us your testFunc, but my guess is that it's not a global, but rather you have it inside something like, for instance:
$('#pageListener').live('pageinit', function(event)
{
function testFunc()
{
// Do something here
}
});
or just a scoping function
(function()
{
function testFunc()
{
// Do something here
}
})();
Either way, since it's declared within another function, it's local to that function, not global. To call it from another script file, you'll need to be able to get at it from the global namespace (sadly). The best way to do that is not to make it a global, but to create just one global that you'll put all of your shared stuff on, like this:
(function()
{
if (!window.MyStuff)
{
window.MyStuff = {};
}
window.MyStuff.testFunc = testFunc;
function testFunc()
{
// Do something here
}
})();
...which you call like this:
$('#pageListener').live('pageinit', function(event)
{
MyStuff.testFunc(); // Or: window.MyStuff.testFunc();
});

Javascript function access

I have a block of code in $(function() { function parseData(){...} )};
I also have a function declared outside of the ready block. This is outside since I hook it up in codebehind ie ddlCategories.Attributes.Add("onchange", "getDataFields()");
From the getDataFields function, I need to call parseData but it does not seem to find it.
How do I access my parseData() which is in my ready block, from outside of the ready block?
(sorry if some of terminology is off - I am now to JS)
Any reason parseData() has to be in the ready block? Why not just make it a top level function:
<script type="text/javascript">
function parseData() { ... }
$(document).ready( function() {
ddl.Categories.....
}
<script>
Just define it outside your ready block. It's currently inaccessible due to the scope of the function.
Definitions can always safely go outside $(function() { ... }) blocks because nothing is executed.
$(function() { ... });
function parseData() { ... }
However, you seem to have a syntax error: )}; should be });.
Declare your parseData function outside of the self-executing $(function(){}); block.
var parseData = function () { ... };
$(function() { ... });
If there are things you need to reference inside the self-executing function, then declare the function globally but define it inside the self-executing function:
var parseData;
$(function() { parseData = function () { ... }; });
As an aside, declaring functions or variables globally is a bad idea.
You should declare the function outside the $(function() { ... }) callback.

Calling a javascript function from another .js file

I have two external .js files. The first contains a function. The second calls the function.
file1.js
$(document).ready(function() {
function menuHoverStart(element, topshift, thumbchange) {
... function here ...
}
});
file2.js
$(document).ready(function() {
setTimeout(function() { menuHoverStart("#myDiv", "63px", "myIMG"); },2000);
});
The trouble is that this is not running the function. I need the two separate files because file2.js is inserted dynamically depending on certain conditions. This function works if I include the setTimeout... line at the end of file1.js
Any ideas?
The problem is, that menuHoverStart is not accessible outside of its scope (which is defined by the .ready() callback function in file #1). You need to make this function available in the global scope (or through any object that is available in the global scope):
function menuHoverStart(element, topshift, thumbchange) {
// ...
}
$(document).ready(function() {
// ...
});
If you want menuHoverStart to stay in the .ready() callback, you need to add the function to the global object manually (using a function expression):
$(document).ready(function() {
window.menuHoverStart = function (element, topshift, thumbchange) {
// ...
};
// ...
});
You have declared menuHoverStart inside a function (the anonymous one you pass to the ready ready). That limits its scope to that function and you cannot call it from outside that function.
It doesn't do anything there, so there is no need to hold off on defining it until the ready event fires, so you could just move it outside the anonymous function.
That said, globals are worth avoiding, so you might prefer to define a namespace (to reduce the risk of name collisions) and hang the function off that.
var MYNAMESPACE = {}; // In the global scope, not in a function
// The rest can go anywhere though
MYNAMESPACE.menuHoverStart = function (element, topshift, thumbchange) {

Categories