Javascript function access - javascript

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.

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

How to use jQuery to call a JavaScript function from another file

My question:
I have 2 files:
//Sub.js
function Second() {
//do something here
}
//Main.js
function One() {
//do something here
}
$(function() {
Second();
});
So basically, the function Second is too long; therefore, I want to move it to a Sub.js file and call it from the Main.js. The problem is this function ( function Second) has to be executed after function One because it gets some data from the function One output.
I don't know how to do this, please help.
If you specifically want to use jQuery,
$.getscript("Sub.js",function(){
Second();
});
<script src="/lib/Sub.js"></script>
<script src="/main.js"></script>
I think you should initialize firstly Sub.js before main.js in your head code.
Because whenever the page is first load js are intialize one by one.
You can include both the files in the page and on document ready call it sequentially:
$( document ).ready(function() {
var result = first();
second(result);
});
I was getting a similar problem. My solution was this. I was defining my function inside the .ready() callback. But The problem is that the functions is not accessible outside of its scope. To make this function available in the global scope (or through any object that is available in the global scope) is necessary declare outside the .ready() callback:
Wrong Way:
$(document).ready(function() {
function functionName () {
// ...
}
// ...
});
Right Way:
function functionName () {
// ...
}
$(document).ready(function() {
// ...
});

How to Call this JavaScript Method which is Wrapped in a jQuery Function

I am studying a JavaScript file and saw in it that some of the methods are wrapped inside a jQuery function. Can Anyone help me how to invoke the following method? And may I know what is the advantage or why the method is wrapped in a function? Below is my sample JavaScript code.
JQuery/JavaScript
$(document).ready(function () {
//How to invoke "testMethod" method?
$(function () {
function testMethod() {
alert("this is a test method");
}
});
});
As you've declared it, testMethod() is a local function and is only available inside the function scope in which it is declared. If you want it to be callable outside that scope, you will need to define it differently so that it is available at a broader scope.
One way of doing that is to make it a global function:
$(document).ready(function () {
//How to invoke "testMethod" method?
$(function () {
window.testMethod = function() {
alert("this is a test method");
}
});
});
testMethod(); // available globally now
It could also be attached to a global namespace or it could be defined at a higher scope where it would also solve your problem. Without specifics on your situation, we can't suggest which one would be best, but the main thing you need to do is to change how the function is declared so it is available in the scope in which you want to call it from.
P.S. Why do you have one document ready function nested inside another? That provides no extra functionality and adds unnecessary complexity. Also, there's really no reason to define testMethod() inside your document ready handlers if you want it available globally.
Before anything else:
$(document).ready(function(){...});
//is the same as
$(function(){...}}
As for your question, here's are potential ways to do it:
If that function is some utility function that everyone uses, then have it available to all in some namespace, like in this one called Utility:
//Utility module
(function(ns){
//declaring someFunction in the Utility namespace
//it's available outside the ready handler, but lives in a namespace
ns.someFunction = function(){...}
}(this.Utility = this.Utility || {}));
$(function(){
//here in the ready handler, we use it
Utility.someFunction();
});
If they all live in the ready handler, and want it to be used by all code in the handler, have it declared in the outermost in the handler so all nested scopes see it.
$(function(){
//declare it in the outermost in the ready handler
function someFunction(){...}
//so we can use it even in the deepest nesting
function nestedSomeFunction(){
someFunction();
}
someElement.on('click',function(){
$.get('example.com',function(){
someFunction();
});
});
nestedSomeFunction();
someFunction();
});
Your call needs to be within the $(function.
It's all about scope and you need to break the testMethod out of the $(function.
Can you perhaps further explain your requirement so that we can maybe help a little better?
Into ready event:
$(document).ready(function () {
//How to invoke "testMethod" method?
var testMethod = function () {
alert("this is a test method");
}
// V0.1
testMethod();
// V0.2
$('#some_id').click(testMethod);
});
In other part:
myObj = {testMethod: null};
$(document).ready(function () {
//How to invoke "testMethod" method?
myObj.testMethod = function () {
alert("this is a test method");
}
});
// Something else
if( myObj.testMethod ) myObj.testMethod();

Javascript Scope Problem

Sorry for asking, but how do I access myFunction() from someFunction()?
<script>
$(document).ready(function() {
// Get messages
var myFunction = function() {
// doSth.
}
// Make the initial call on page load.
myFunction();
);
function someFunction() {
// Call the function a second time
myFunction(); // Call fails!
}
</script>
You are scoping it to the anonymous function you are passing to the ready method. Just move the definition outside that function.
Its more then a scope issue. Yes, you are scoping it to the anonymous function but even if you make it global by removing the var like this:
$(document).ready(function() {
// gets defined AFTER THE DOM IS READY
myFunction = function() {
// doSth.
}
}
// is called BEFORE THE DOM IS READY
myFunction();
It STILL won't work, because myFunction hasn't been defined by the time you call someFunction. someFunction is running immediately before the document is ready, which is BEFORE myFunction is defined.
Both functions need to be either in the document ready block, or outside it. If you need to manipulate DOM elements, I'd recommend inside.
If someFunction is called for a handler, you can remove the var declaration from myFunction and it will work as expected, because this will put myFunction in the global scope.
I don't think this will work because till the dom becomes ready and the document 'ready' event is fired the 'myFunction' function will not be created. The second call to 'myFunction' happens much before the 'myFunction' is created. This case will fail even if you create the function 'myFunction' in global namespace.
If you are not using any closure values inside your 'myFunction', you can move this function to global namespace. This will solve your ploblem.
Ex:
var myFunction = function(){
//Do somthing
}
$(document).ready(function(){
myFunction();
});
myFunction()
I think you wont be able to call myfunction() with your current code. You will have to get that function() { var myfunction = ... }; out of document.ready(). Seperate the method, then you can call myFunction.

How can I Call Jquery Function From Other JavaScript function

How can I call the Jquery Function From other javaScript Function (Not
from jquery function)
i.e
I have written some Jquery code like below
$(document).ready(function()
{
function func1(){
// Do Something.
}
});
Now I want to call the func1() function from other JavaScript Function
i.e Say an Example
function callJqueryFunction(){
**func1();**
}
The above javaScript function calling not work
but If do the same code inside a
$(document).ready(function()
{
function func1(){
// Do Something.
}
**func1();**
});
Its Work fine.
So what can I do for call the function which is inside a Jquery code
format.
this has nothing to do with jquery in general, it's just a scoping issue
function foo()
{
function bar() {
....
}
bar() // Ok
}
bar() // Not OK
function 'bar' is "local" in foo and is not visible outside of it.
if you want a function to be used in different contexts, declare it globally.
Isn't func1 scoped inside that ready function? If you declare func1 outside of ready it should be available to other javascript code just as any other function.
So:
$(document).ready(function()
{
func1();
});
function func1()
{
// Do something
}
function SomeOtherJavascriptFunction()
{
func1();
}
The function func1 is defined in the scope of the parent function. If you don't need this, you can simply move the definition outside (I expect in case of $(document).ready you don't really need it). Otherwise you will need to pass/store the function reference somewhere, and use that to call it.
You can do something like this
var funcToCall;
$(document).ready(function()
{
funcToCall = function func1(){
// Do Something.
}
});
funcToCall();

Categories