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 ?
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 ?
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');
}
The scope of a variable in javascript is either
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.
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.
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.