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/
Related
I was told to avoid public variables and conflicts, it is better to place the whole plugin in an anonymous function. I tried to do this but functions do not work anymore.
Here is a simple example:
(function($) {
function changeIt() {
$("button").text("off");
}
}(jQuery));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="changeIt()">On</button>
the function runs by a HTML element but since it is inside another function, the element cannot find it.
1- How can I make it working?
2- Is it a good approach to make sure public variables are covered and assumed as private ones?
Thanks
inline events defined on elements only have access to the global scope, so, when you moved that function out of the global scope and into the scope created by the anonymous function, it was no longer accessible to the inline event.
You have two options:
Stop using inline events
(function($) {
function changeIt() {
$("button").text("off");
}
$("button").click(changeIt);
}(jQuery));
Or define it globally
//(function($) {
function changeIt() {
$("button").text("off");
}
//}(jQuery));
This has to do with scope. The changeIt function only exists within the function($). If you want to add it to public scope its best to create an object the prototype the functions.
(function($) {}(jQuery)); -> This will create a private scope, basically your function won't be defined inside window, but inside this private scope.
<button onclick="changeIt()">On</button> -> This will try to execute changeIt from window, which will be undefined.
It's because the function is no more in the global object and thus the onclick event handler in the html element cannot find it by name.
Change your html to
<button id="mybutton">On</button>
and your code to
(function($) {
$("#mybutton").click(function(){
$("#mybutton").text("off");
});
}(jQuery));
and it will work because the handler will not need to be looked up by name
Since changeIt is not found in the global scope (window in the case of a browser), the function isn't triggered on a click. In fact, your console should show an exception like: "Uncaught ReferenceError: changeIt is not defined".
To remedy this, and keep your function structure, set the handler from within the "onload" handler:
(function($) {
$('#myBtn').on('click', function () {
$("button").text("off");
});
}(jQuery));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myBtn">On</button>
I current have some code that looks like this:
// when the document is ready
execute myFunction();
(function($){
function myFunction()
{
// code
};
})(jQuery);
The console is saying that myFunction is not defined...why?
It's not accessible because you've put your function inside another self-invoking function, and the call to it is outside that.
Your comment states that you want the call to myFunction() to happen on load, which if your current code worked, would not be the case anyway. It would call the function before DOMReady.
To get the behaviour you want, place the function call within the SIF:
(function($){
myFunction();
function myFunction() {
// code
};
})(jQuery);
I have a function in my <head>
$('document').ready(function () {
function shout(msg) {
alert(msg);
}
});
And a button in the <body>
but I am getting function shout not defined .Why?I am using Firefox 25.
SO has many similar questions and I have tried all but no help.Except this one,which might solve my problem.I didn't get what the answer is talking about.Please anyone elaborate what he is talking about as the two fiddles ,in answer as well as the question are exactly same ,except some property changes on the leftside bar: onload and No wrap-in <head>
Or what might be the problem?
Your function is visible in it enclosure that is the document.ready. If you move function out side document.ready then it will accessible in global scope.
function shout(msg)
{
alert(msg);
}
Your function is defined inside an anonymous function, so it's name is limited to that scope. If you're trying to access it from the onclick attribute of a button that won't work, because names there look in the global scope.
You have two solutions:
One is to define the function outside $(document).ready(), so it will be in the global scope.
The other is to bind your click handler using jQuery rather than an inline attribute:
$(document).ready(function() {
$("#somebutton").click(function() {
shout("Button was clicked");
});
function shout(msg) {
alert(msg);
}
});
Because the function is wrapped inside a parent function. The scope inside the function is not available outside of it.
Separate it instead -
function shout(msg) {
alert(msg);
}
$('document').ready(function{
shout('AWESOME');
});
$('document').ready(function {
shout('message');
});
function shout(msg) {
alert(msg);
}
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);
});
What is the difference between defining a function within document.ready or not ?
Does it affect the scope of when a function can be invoked ?
Example, is there any issues/differences I should be aware of in location definitions of functions inside() & outside() :
<script>
document.ready(){
function inside(){
alert('inside');
}
}
function outside(){
alert('outside');
}
</script>
Yes, you can only access the inside function from inside the callback for the ready event:
document.ready(function(){
function inside(){
alert('inside');
}
inside(); // works
outside(); // works
});
function outside(){
alert('outside');
}
inside(); // doesn't work
outside(); // works
Does it affect the scope of when a function can be invoked ?
Yes, and nothing else.
(Although your particular example depends on you adding a ready() method to the documentobject first.)
Javascript has function level scoping, meaning if you define a function in document.ready it won't be available outside document.ready
I would define a namespace outside like so:
var app = {};
Then define your inside function like so:
app.inside = function() {
Then inside will be available in your app global namespace.