I'm a bit new to the jquery codeverse. I would like to know how to call back function CSZ after a document resize. Here is my current setup:
$(document).ready(function CSZ () {|CODE|});
Then later, I want to call the code back with this function:
$(window).resize(CSZ);
It seems to be a very simple concept that just isn't working for me.
Declare the function on its own. You can then reference it for both callbacks:
function CSZ() {
// Do stuff
}
$(document).ready(CSZ);
$(window).resize(CSZ);
Currently, CSZ is a named function expression. The identifier CSZ will only be in scope inside the function it identifies. By changing to to follow my example, you make CSZ a function declaration instead. It will then be available anywhere within the scope in which it appears (and descendant scopes thereof).
In your current code the symbol CSZ will only be accessible from inside the function body itself; it's actually a language feature.
In order for this to work as expected, your function needs to be declared like this, on its own and in the global scope:
function CSZ () {|CODE|}
And then it can be used like this:
$(document).ready(CSZ);
$(window).resize(CSZ);
function CSZ () {|CODE|}
$(document).ready(CSZ)
$(window).resize(CSZ);
Your problem is that the function you declared isn't declared as a window variable.
You could do this :
$(document).ready(window.CSZ=function(){...});
$(window).resize(CSZ);
Or you could follow this more common pattern :
$(function(){
function CSZ(){
...
};
CSZ();
$(window).resize(CSZ);
});
Related
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.
In my knockout.js project I wrote some self invoking functions like this:
var addMarkers = function () {
ko.utils.arrayForEach(self.sectionList(), function (sectionItem) {
ko.utils.arrayForEach(sectionItem.placeList(), function (placeItem) {
placeItem.marker.addListener('click', function () {
map.panTo(placeItem.marker.getPosition());
});
});
});
}();
The function works without problems, however in JSLint the "var addMarkers" was highlighted as unused variable. That makes me wonder if I should the function like this, or just make anonymous because it is a better practice?:
function addMarkers (){ code to be executed };
Assigning the result of a self-executing function is often useful. In particular, I like to define my main viewmodel this way, because
I don't need a prototype for my viewmodel
I'm not likely to need more than one instance of a viewmodel
The reason you would use a self-executing function is that you need a local scope for whatever you're doing, to isolate it from surrounding scope. The reason you would assign a variable from it is that you want it to return a value you will use later. In your example, neither of these is true.
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/
I am in a position where I need to "update" a function that exists in another javascript file. The file looks like this:
function jf(){
alert('1');
}
//call jf periodically
jf();
The second js file, which is loaded after looks like this:
console.log(jf);
console.log(window.jf);
var func=function(){
alert('2');
};
jf=func;
window.jf=func;
The first log successfully returns the original jf method, the second doesnt. The first set seems to set the local variable jf, and the second does basically nothing. Is there a way to achieve this functionality?
According to Javascript closures - behavior of overridden functions from the global scope
var done = and function done do basicaly the same thing. They will shadow the outer definition in the inner scope but they will not replace it on the outer scope.
This means you can only override your initial definition of function jf() if you are in the same execution context. Otherwise, replace function jf(){ ... with window.jf = function(){...
Also, running your tests in an inspector console might help.
First, use variables:
var jf = function () {
alert('1');
};
jf();
Then the second bit should work fine:
var func = function () {
alert('2');
};
jf = func;
jf();
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.