I'm trying to create a button that sends an alert dialog box to the window but for some reason I'm getting this error: "Uncaught ReferenceError: startPause is not defined." What am I doing wrong?
Here is my fiddle: http://jsfiddle.net/rgwawupw/
And the code is here:
<button onclick="startPause()">Start</button>
$(function(){
function startPause(){
alert("A");
};
});
You have two separate problems. First, get your javascript out of your HTML. Second, startPause() is not defined in the global scope.
<button id='clicker'>Click Me!</button>
function startPause(){
alert('A');
}
$('#clicker').click(function(){
startPause();
});
Make sure you put the script tag at the end of your body element then you don't need the wrapper like you have in your code.
You don't need jQuery for this, and you should put your JS in body or head (fiddle - note the settings in the top left):
<button onclick="startPause()">Start</button>
function startPause(){
alert("A");
};
This way your function will be in global scope. When you set onLoad or onDomready in JSFiddle, you are wrapping your function in an event callback, and thus move it from global scope.
If you need or want to use jQuery, go Jared's way. That way you bind click event using jQuery and don't let the browser do it. This way you have more control and can move your function from global scope.
A function defined by a function expression inherits the current scope. That is, the function forms a closure.
On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
Which means because you are not making an assignment as
$(function(){
startPause = function(){ //var was skipped purposely
alert("A");
};
});
In case you still need to use it in $(function() {}); make a global object with a namespace
var stackoverflow = {};
$(function(){
stackoverflow.startPause = function(){ //var was skipped purposely
alert("A");
};
});
<button onclick="stackoverflow.startPause()">Start</button>
but best practice would be to use
$(element).on('click', function() {});
Related
I'm having some issues with running some functions from an external js file.
The html includes:
<script src="js/file.js"></script>
<script>
$("#center-button").click(function() {
explodePage("center");
});
</script>
The js file includes:
var explodePage = function(button) {
//code here
aboutPage();
}
var aboutPage = function() {
//code here
}
The explodePage function runs fine, but as soon as it reaches the call to the nested aboutPage function, it starts throwing these uncaught typeerrors at me. It works fine if I don't use an external js file and just put everything into the html. Pretty new to this so probably missing something obvious in scope or something. Any solutions?
Declare the function's definition as below:
function explodePage(button) {
//code here
aboutPage();
}
function aboutPage() {
//code here
}
Explanation:
When you use the var keyword for declaring functions, the execution of JS happens as when the variable is initialized, you cannot reference or use variable's before declaration. In contrast with the name function defintion JS interpreter first picks the enclosed functions before execution and initializes it before the code execution. This is called AST- Abstract syntax tree that is followed by JS interpreters.
Also Remember:
Also bind your Jquery code inside a Jquery document ready function, just to make sure the Jquery and the DOM elements are available for the bindings.
It's not a good a idea to pollute the global window object with variables, since there can be collisions. And immediately-invoked function expression is a good solution for this.
(function(){
//You can declare your functions in here, and invoke them below
$( document ).ready(function() {
//Check that the DOM is ready, in order to manipulate it an add events
$("#center-button").click(function() {
explodePage("center");
});
});
})($); //Notice that we are injecting a dependency, in this case jQuery
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 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 can't find out what is the problem with this JSFiddle.
HTML:
<input type="button" value="test" onclick="test()">
JavaScript:
function test(){alert("test");}
And when I click on button - nothing happened. The console says "test not defined"
I've read the JSFiddle documentation - there it says that JS code is added to <head> and HTML code is added to <body> (so this JS code is earlier than html and should work).
If you do not specify the wrap setting it defaults to "onLoad". This results with all JavaScript being wrapped in a function run after result has been loaded. All variables are local to this function thus unavailable in the global scope.
Change the wrapping setting to "no wrap" and it'll work:
http://jsfiddle.net/zalun/Yazpj/1/
I switched the framework to "No Library" as you don't use any.
The function is being defined inside a load handler and thus is in a different scope. As #ellisbben notes in the comments, you can fix this by explicitly defining it on the window object. Better, yet, change it to apply the handler to the object unobtrusively: http://jsfiddle.net/pUeue/
$('input[type=button]').click( function() {
alert("test");
});
Note applying the handler this way, instead of inline, keeps your HTML clean. I'm using jQuery, but you could do it with or without a framework or using a different framework, if you like.
There is another way, declare your function into a variable like this :
test = function() {
alert("test");
}
jsFiddle
Details
EDIT (based on the comments of #nnnnnn)
#nnnnnn :
why saying test = (without var) would fix it ?
When you define a function like this :
var test = function(){};
The function is defined locally, but when you define your function without var :
test = function(){};
test is defined on the window object which is at the top level scope.
why does this work?
Like #zalun say :
If you do not specify the wrap setting it defaults to "onLoad". This results with all JavaScript being wrapped in a function run after result has been loaded. All variables are local to this function thus unavailable in the global scope.
But if you use this syntax :
test = function(){};
You have an access to the function test because it's defined globally
References :
https://stackoverflow.com/a/338053/3083093
https://stackoverflow.com/a/5830423/3083093
Change wrap setting in the Frameworks & Extensions panel, to "No wrap-in <body>"
There is no problem with your code.Just choose the extension onLoad() from right side.
<script>
function test(){
alert("test");
}
</script>
<input type="button" value="test" onclick="test()">
Select OnDomready
HTML:
<input id="dButton" type="button" value="test"/>
JavaScript:
addEventListener('load', init, false);
function init()
{
oInput = document.getElementById('dButton');
oInput.onclick = test;
}
function test(){
alert("test");
}
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);
});