Can someone explain to me why this doesn't work and show me how to make it work? I've tried creating a namespace and IIFEs functions but I cannot seem to get it.
$(document).ready(function() {
alert (hi);
});
$(document).ready(function() {
var hi = "hello"
});
Thank You!
When you do this:
$(document).ready(function() {
var hi = "hello"
});
You are creating a variable named hi that is local to that callback function. It is simply not accessible outside that function. This is a feature of the language.
You can declare the variable at a higher scope like this:
var hi;
$(document).ready(function() {
hi = "hello"
});
And, then the value of that variable will be available outside the scope, but you will not necessarily know when it gets the proper value because you won't know when the $(document).ready() callback is called unless you put your code inside that callback.
It really makes little sense to try to share a variable between two calls to $(document).ready(). It would make much more sense to just put the code inside the same $(document).ready() callback:
$(document).ready(function() {
var hi = "hello"
alert (hi);
});
Not Really Recommended
If you were going to try to share a variable between two calls to $(document).ready() (something I don't really recommend because it makes your code somewhat fragile), it can be done. Callbacks to $(document).ready() will be called in the order they are attached so you will have to order things appropriately:
var hi;
$(document).ready(function() {
hi = "hello"
});
$(document).ready(function() {
alert (hi);
});
This will make sure that the first $(document).ready() callback that sets the value of hi will be called first before the second one where you try to use the value.
Related
can you help me?
I'm using a script in one file to call other function in another file, but I'm getting function is not defined. So I've start searching to fix this way but I didn't get any positive results. Check my code below:
index.html
$(document).ready(function(){
setInterval(function(){
lAs = new loadAsync();
}, 900);
});
js/plugins.js
function window.loadAsync() {
$(".loadAsync").each(function(index, element){
$(element).attr("src", $(element).attr("data-src"));
});
}
So, what should I do to fix this problem? Thank you.
#edit:
<script src="js/plugins.js"></script>
I've already wrote this in index.html
First, your syntax is wrong. An identifier may not have a . in it. Just use loadAsync and it'll be global unless you've nested it in another scope.
You can also make the jQuery more efficient by calling .attr() with a callback instead of using .each().
Finally, it seems unlikely that you actually want to use new to invoke the function. I changed the code below to simply pass it as the callback to setInterval. I also declared the lAs variable properly.
function loadAsync() {
$(".loadAsync").attr("src", function(){
return $(this).attr("data-src");
});
}
var lAs;
$(document).ready(function(){
lAs = setInterval(loadAsync, 900);
});
And of course all this can be done easily without jQuery.
function loadAsync() {
for (const el of document.querySelectorAll(".loadAsync")) {
el.src = el.dataset.src;
}
}
var lAs;
document.addEventListener("DOMContentLoaded", function(){
lAs = setInterval(loadAsync, 900);
});
First of all, function window.whatever() {} is wrong (could you include the link of the SO thread where you saw that being used ?).
Since you are getting an error even without that, please make sure that:
1. loadAsync is declared in the global scope in the plugins file.
2. You are including js/plugins.js correctly. Go on and insert foo bar; in js/plugins.js and then check if you get a SyntaxError (while including it before the other JS file), if you don't, you are not correctly including it.
So, I've got my app to work. But I don't want to use a global variable.
Here's what I'm trying to do:
var AMLid;
$(".commentButton").on('click', function () {
AMLid = $(this).closest('tr').siblings().find('p.important').text();
alert("id is:" + AMLid);
});
$(".saveButton").on("click", function () {
$(".modal-body #txtAddComment").val(AMLid);
});
I want to get an ID from a selected table row, and pass the ID to the modal dialog, so I then can use the ID as a parameter when clicking a button in the modal dialog.
How do I do the exact same thing, without using a global variable? is it possible?
And what are the cons of using a global variable like this? Does it crash or target the wrong ID's if many people use it simultaneously?
Any help is appreciated.
You can wrap the whole thing in a function
(function(){
var AMLid;
$(".commentButton").on('click', function () {
AMLid = $(this).closest('tr').siblings().find('p.important').text();
alert("id is:" + AMLid);
});
$(".saveButton").on("click", function () {
$(".modal-body #txtAddComment").val(AMLid);
});
})();
You can avoid the use of a global variable by using an Immediately-Invoked Functon Expression, which would look like this:
(function() {
var AMLid;
$(".commentButton").on('click', function () {
AMLid = $(this).closest('tr').siblings().find('p.important').text();
alert("id is:" + AMLid);
});
$(".saveButton").on("click", function () {
$(".modal-body #txtAddComment").val(AMLid);
});
})();
This works because the AMLid is now private to the function; when the function is executed it creates a new execution context which includes that variable, which is then accessible to statements made in the function, but not outside it. And because this creates a closure the variable continues to be accessible by the callbacks attached to those functions. Moreover, as the function is anonymous it itself doesn't have a name polluting the namespace.
The term Immediately-Invoked Functon Expression comes from Ben Alman, and you can read his original blog post discussing the concept here: http://benalman.com/news/2010/11/immediately-invoked-function-expression/
Some cons of using a global include: hard to keep track of variables, other scripts might mess with its value (when they probably shouldn't have access to it), harder to maintain, less clean code. Your worry about it being overwritten if multiple people use it won't be an issue because it's client-side and so there will be one instance per page loaded in any given browser.
Javascript is client-side so actually I can't get the point in your "many people use it simultaneously". One browser for user, so you don't have to worry about multiple client. Each one use his own set of global variable.
If your executions are not linked in any way (they are "onclick") you can just wrap them in a function so you're actually setting a "local/global" variable.
Every function that'll need that AMLid has to be declared inside that function scope.
The only way to keep variables out of the global scope is by wrapping them in a function. If this is all the code you're using in this particular module, it doesn't really make a difference.
I am trying to assign the ajax callback function variable value to the existing variable.
I have
function test(){
}
test.prototype.click=function(){
this.count;
//call ajax codes.....
//ajax callback function
ajax.callback=function(var1){
//I want to assign returned data to this.count property.
this.count=var1.length
}
}
test.prototype.show=function(){
//wont work, it will show undefined...
alert(this.count);
}
var t=new test();
t.click();
t.show();
I think it's the scope issue but I don't know how to solve this. Any idea? Thanks in advance.
Yeah, using this within another scope causes all kinds of issues, so you need to work around this. One way is to avoid using this entirely by defining your function differently. For instance, you can define count like so:
function test() {
function count() {
}
...
And just use count() without the this. prefix.
You can also set a variable to this and use that to refer to count within your other scope. For instance:
var self = this;
Scoping issues with this can be a pain in the neck and can occur when you do more OO with callbacks. It's good you got introduced to this early on, so now you know to be on guard.
I have a javascript code and want to extend this code now. how can I write a makeAMessenger function in global scope so that it triggers when user clicks document and alert below message
THIS. IS. SPART.
currently I have following code.
CODE HERE
Do you mean this ?
function makeAMessenger(madness, sparta) {
return madness.bind(sparta);
}
have a solution here and you don't need to pass variable along, it can be accessed in function.
function makeAMessenger(madness) {
return madness;
}
You can use Function#apply() or Function#call() to bind this.
http://jsfiddle.net/QfNbp/
i want to get a variable (which is set when a link is clicked) over to a function and show it as a pop out.
the code as shown below:
$('a#link1').click(function(e){
e.preventDefault();
var value = 'true';
});
function exe(){
alert(value);
}
when the function is executed , all i get is value is undentified.
So anyone knows a way around it?
Variables have scope, you define the value variable in the scope of the onclick closure, and it wont be accessible outside it.
The following would work:
var value = false; //Define in the global scope
$('a#link1').click(function(e){
e.preventDefault();
value = false; //Use in a local-scope is legal.
});
function doSomething()
{
alert(value);
}
However having many global variables will make your project hard to maintain, and there are other more clean solutions available. In general i'd recommend you to read a proper book on programming though :)
Just make the variable global, or better yet "attach" it to the element using the .data():
$('a#link1').click(function(e) {
e.preventDefault();
$(this).data("value", "true");
});
Then you can always check for this:
function exe() {
alert($('a#link1').data("value"));
}
Note that it was added in jQuery 1.2.3 guess that by now it doesn't really matter though.