Calling function inside jQuery document ready - javascript

While debugging, I always use Firebug and try to call functions and show variables. However I can't when the function or variable is defined within $(document).ready.
How can I access these variables? Can I type something like a namespace, like document.ready.variableName or how can I see this?
Thank you in advance.

Global variables and functions can be created by assigning them as a property of window:
$(function(){
window.foo = function foo() {
// …
}
});
foo() should be accessible anywhere after that handler is executed.

How can I access these variables?
Well, you can't. Everything that you define inside an anonymous function such as what you are using in the $(document).ready is scoped to this anonymous function. It's private and not accessible to the outside.
So you could put your console.log inside the $(document).ready if you needed to inspect some private variable that is defined in its scope.

That's what debugging is for. In all major browsers (including IE), you can set breakpoints in the javascript code. When this is done the script halts and you can inspect your variables.
Here some links:
http://getfirebug.com/javascript
http://www.jonathanboutelle.com/how-to-debug-javascript-in-internet-explorer
How do you launch the JavaScript debugger in Google Chrome?

It depends on how you declare the variables inside the .ready() function. If you do var x = "test", then no, they are only accessible inside the scope of the ready function. If you do something like x="test", then that is available in the global scope and you can just access it like alert(x); or alert(window.x);
You probably don't want to define variables inside the ready function though if you are trying to use them outside the ready function.

Declare the variable in global scope:
E.g.
<script type="text/javascript">
var globalVar = null;
$(document).ready(
function() {
globalVar = "This is the value";
}
);
function TestFunc() {
alert(globalVar);
}
</script>
Here, if you call the TestFunc() anytime after the page load, you will see the value assigned in the ready() function.

Not sure I fully understand the issue, but couldn't you just declare the variables outside of document ready?
var a = "bar";
$(document).ready(function(){
a = "foo";
});
If you're using firebug, you should be able to call console.log within document ready, which might give you what you're looking for.

If you have
var x = "foo"
$(document).ready(function(){
alert(x); // foo
});
You can see the x variable anywhere, but if you you declare a variable y into the document ready It'll be only accessible within the document ready:
var x = "foo"
$(document).ready(function(){
alert(x); // foo
var y = "bar"
alert(y); // bar
});
alert(y); // undefined

Related

Single function not defined in external JavaScript file [duplicate]

While debugging, I always use Firebug and try to call functions and show variables. However I can't when the function or variable is defined within $(document).ready.
How can I access these variables? Can I type something like a namespace, like document.ready.variableName or how can I see this?
Thank you in advance.
Global variables and functions can be created by assigning them as a property of window:
$(function(){
window.foo = function foo() {
// …
}
});
foo() should be accessible anywhere after that handler is executed.
How can I access these variables?
Well, you can't. Everything that you define inside an anonymous function such as what you are using in the $(document).ready is scoped to this anonymous function. It's private and not accessible to the outside.
So you could put your console.log inside the $(document).ready if you needed to inspect some private variable that is defined in its scope.
That's what debugging is for. In all major browsers (including IE), you can set breakpoints in the javascript code. When this is done the script halts and you can inspect your variables.
Here some links:
http://getfirebug.com/javascript
http://www.jonathanboutelle.com/how-to-debug-javascript-in-internet-explorer
How do you launch the JavaScript debugger in Google Chrome?
It depends on how you declare the variables inside the .ready() function. If you do var x = "test", then no, they are only accessible inside the scope of the ready function. If you do something like x="test", then that is available in the global scope and you can just access it like alert(x); or alert(window.x);
You probably don't want to define variables inside the ready function though if you are trying to use them outside the ready function.
Declare the variable in global scope:
E.g.
<script type="text/javascript">
var globalVar = null;
$(document).ready(
function() {
globalVar = "This is the value";
}
);
function TestFunc() {
alert(globalVar);
}
</script>
Here, if you call the TestFunc() anytime after the page load, you will see the value assigned in the ready() function.
Not sure I fully understand the issue, but couldn't you just declare the variables outside of document ready?
var a = "bar";
$(document).ready(function(){
a = "foo";
});
If you're using firebug, you should be able to call console.log within document ready, which might give you what you're looking for.
If you have
var x = "foo"
$(document).ready(function(){
alert(x); // foo
});
You can see the x variable anywhere, but if you you declare a variable y into the document ready It'll be only accessible within the document ready:
var x = "foo"
$(document).ready(function(){
alert(x); // foo
var y = "bar"
alert(y); // bar
});
alert(y); // undefined

How to override this function in Javascript

I've got the following Javascript situation:
// First file - the one that I can't edit
(function(){
"use strict";
function test() {
alert("a");
}
test();
})();
This is defined in a Javascript file which I cannot edit. How would I go about overriding the test() method?
Redefining the function doesn't work. The output is still "a".
// My file - trying to override the first file's test() function
(function(){
function test() {
alert("b");
}
})();
Do you have any other suggestions?
In my mind the test() method must be defined somewhere, right? And if it is defined, I can override it.
Assign the function to a variable to create locally scoped functions that will behave the same within it's own function scope.
A scoped variable has priority over a global variable. So if you define a local variable in your own function you're overriding the other defined one. within the scope you're working in of course. On the outside of your scope the global object still persists.
You can't override a function in another scope. That is why a scoped function is scoped. It will keep a reference to it's local scoped variable. That's why the scopes are generally used, so you can encapsulate and protect your code to assure your code keeps working as intended.
unless it's a publicly exposed method, you can't override it.
(function(){
var test = function() {
alert("b");
}
})();
(function(){
"use strict";
function test() {
console.log("a");
}
test();
})();
(function(){
var test = function() {
console.log("b");
}
test();
})();
The text of the file can be edited if file is requested using XMLHttpRequest or fetch, then set edited response text to .textContent of script element, append script element to document.

Not able to define function

I am writing something like
(function($){
function showAlert(){
alert('test');
}
})(jQuery);
and when I tried to run showAlert(), it's saying showAlert() is not defined.
Can anyone suggest why ?
The scope of a variable in javascript is either
the global scope
the function in which it is defined
showAlert is a variable. It's only available in the scope of the external function you wrote.
If you want to define a function for the external scope, define it in the external scope.
I suppose you're calling that function outside IEFE function.
Calling it outside won't work as it is not in global scope. The IEFE is creating a closure of which , showAlert becomes a part and not of global scope which is window
Do this:
(function($){
window.showAlert = function(){
alert('test');
}
})(jQuery);
It doesn't make sense to put a function declaration inside IEFE unless otherwise it is a jquery plugin. So, just remove it:
function showAlert(){
alert('test');
}
You're Creating A function inside a self executing anonymus function ie. $(document).ready() or $(function()....
So your function is in local scope of that function. Simply Means You cant access that in outside of that function.
So to make it accessible just make it global.
In JavaScript window is global object. So to make your function global, use that object as follows:
$(document).ready(function() {
function showAlert()() {
alert('test');
}
window.showAlert=showAlert(); //NOTE THIS, IT IS IMPORTANT.
});
Now you can access it elsewhere in your JS.
Here is working Fiddle
Hope it'll help you! cheers :)..
If you want to extend jQuery with your function just add function to jQuery object.
Like this:
(function ($) {
$.extend({
showAlert: function () {
alert('test');
}
});
}(jQuery));
Separate this code into file with name jquery.showAlert.js, include it after jquery library
and after this you can use function in this way:
$.showAlert()
Best regards.
This should work!
function showAlert(x) {
alert(x);
}
showAlert($('#anyElementId').val());
Assign the variable X for function and your alert. Then pass your element val into your function call.
Demo: http://jsfiddle.net/94ZtT/

trying to pass `this` through a function

I have a function localised to the main function and i want to use this to call it but it doesn't seem to work.
My code has:
function option(room,slot){
var div_id = document.getElementById(room);
var opacity = window.getComputedStyle(div_id).opacity
transition_opacity(div_id,opacity,0,function(){this.load});
function load(){
console.log('test'); //does not happen
}
}
Have i misunderstood the use of this or is the scope lost when i use function(){} to call load?
From your code it is not obvious, what object this could refer to. It depends on how option is called. However, if you define the load function inside of the option function anyway, it is best to just reference it directly. You will have to move the declaration of test above the transition_opacity call though:
function option(room,slot){
var div_id = document.getElementById(room);
var opacity = window.getComputedStyle(div_id).opacity;
function load() {
console.log('test');
}
transition_opacity(div_id,opacity,0,load);
}
As you can see, I just reference load directly. You could make another function which calls the load function inside (i.e. function() { load(); } – note the parentheses which calls the function) but that would give you no benefit but would just add another unneeded function to the stack. So just refer to the actual function itself.
For more information on the this keyword, check out this question. Spoiler: It’s more complicated than you would expect.
The scope of this is lost in this instance, probably pointing to the document. You can capture this to a variable in the outer scope to make this work as intended.
var context = this;
transition_opacity(div_id,opacity,0,function(){context.load();})
The above will not work however. This is because load does not exist on the context of this. You would need to define the load function as such:
context.load = function(){
console.log('test');
}
Both.
First, your load function is not a member/property of any this, the way you have it coded. Your load function is simply a nested function that exists within your option function, as has been sort of implicitly noted in other responses.
In your option function, if you want 'load' to become a member of 'this', you'd need to say so, like this:
function option(){
this.load = function(){}; // now load is actually a property of whatever this is
}
Second, you and the other poster are correct that 'this' is no longer the same 'this' by the time your anonymous function is called.
Whenever you call a function, a brand new 'this' is created and exists within the scope of that function. If you just call a function like this:
transition_opacity(args);
.. then within transition_opacity, 'this' just refers to the window object, or maybe window.document. For 'this' to refer to anything other than window or window.document, you need to (in effect) do one of the following:
myObject.transition_opacity(args);
transition_opacity.call(myObject, arg1, arg2, ..);
transition_opacity.apply(myObject, argArray);
or
var myObject = new transition_opacity(args);
In each of those cases, within transition_opacity, 'this' refers to myObject (or, well, in the last case, it refers to a new object that is being created and assigned to myObject).
Here is a way to do what it looks like you're trying to do:
var MyNamespace = {
option: function(room,slot){
var div_id = document.getElementById(room);
var opacity = window.getComputedStyle(div_id).opacity;
var _this = this;
transition_opacity(div_id,opacity,0,function(){
// Careful! Inside here, 'this' is just window or window.document,
// unless transition_opacity sets it to something using call or apply,
// in which case that 'this' is probably not the 'this' you want.
// So carefully refer to the saved instance of 'this':
_this.load();
});
},
load: function(){
console.log('test'); // now it should happen
}
}
.
.
MyNamespace.option(room, slot); // inside option, 'this' is MyNamespace.
Here's another way to do it:
function MyClass(){};
MyClass.prototype = {
// all the same stuff that is in MyNamespace above..
};
.
.
var myObject = new MyClass();
myObject.option(room, slot);
Clear as mud?
Just use
transition_opacity(div_id,opacity,0,load);
You have defined a 'load' within another function as an 'Function Declaration', so now it is only accessible within 'option' function and in other functions defined in this one by name 'load'. You can't access it by using 'this.load' no matter what 'this' is. If you want to access 'load' function as 'this.load' you can try this example to understand how 'this' keywoard works
// Function Declaration
function f1(callback){
callback();
};
// Function Declaration
function f2(){
// Function Expression
this.load = function(){
console.log("test");
};
f1(this.load);
};
var obj = new f2(); // test, this == obj, so obj.load() now exists
obj.load(); //test, this == obj
f2(); //test, this == window, so window.load() now exists
load(); //test, window is the global scope

jQuery setInterval() undefined function error

Hi I am relatively new to javascript and jQuery and while trying to create a function the runs in intervals of 100 milliseconds I encountered a problem.I seem to get in the console of firebug and error witch says that clasing() is not defined.This is my code:
$(document).ready(function() {
var prev = $("img.selected").prev();
var curent = $("img.selected");
var next = $("img.selected").next().length ? $("img.selected").next() : $("img:first");
$("img").not(":first").css("display","none");
function clasing() {
curent.removeClass("selected");
next.addClass("selected");
}
setInterval("clasing()",100);
});
What am I doing wrong here?Thank you
You have a scope problem. Your variables (prev, curent and next) are accessible inside .ready scope, such as your function clasing. But when you add this function to be called in a interval, using setInterval, this function should be in a Global scope (inside window object). Then, you should declare this function like window.clasing = function(){ ... }, but, doing this, the variables declared in .ready() scope will not be accessible running the function outside this scope, so all your variables must be in a global scope too. This should solve your problem.
However, this isn't a good programming practice, you should declare your variables inside clasing function, then they will be accessible only in function scope; And your function must be delcared outside .ready() function, and then you declare the interval inside .ready() function.
So, your code should be liek this:
function clasing(){
var prev = $("img.selected").prev();
var curent = $("img.selected");
var next = $("img.selected").next().length ? $("img.selected").next() : $("img:first");
curent.removeClass("selected");
next.addClass("selected");
}
$(document).ready(function() {
$("img").not(":first").css("display","none");
setInterval("clasing()",100); //or just setInterval(clasing,100);
});
Change setInterval("clasing()",100); to setInterval(clasing,100);
Change
setInterval("clasing()",100);
To
setInterval(function() {
clasing();
}, 100);
Right now your call to setInterval is running in global scope, but your function is defined inside your jquery function. Creating a closure will give you access to the jquery functions members.

Categories

Resources