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");
}
Related
download
<script type="text/javascript">
function download() {
alert("hello");
}
</script>
When I click the link, I don't see an alert. Instead it says the function doesn't exist. Why?
When I rename download to downloadx, it still doesn't work, so it's not the name of my function that's a problem.
First of all as #gmo said your code will never work outside JSFiddle because of the name of the function.
Read More about it HERE (Can't use “download” as a function name in javascript)
From now on i'll use downloadx as the function's name
Instead another problem caused by JSFiddle makes your code non functioning even if you use downloadx.
simple-example-doesnt-work-on-jsfiddle
JSfiddle wrap your code inside a window.onload function, so the download function is outside of the scope.
//<![CDATA[
window.onload=function(){
function downloadx() {
alert("hello");
}
}//]]>
SOLUTION 1 JSFiddle
you should declare it directly on window
window.downloadx = function() {
alert("hello");
}
SOLUTION 2 JSFiddle
Select No wrap - in <head>
On the left column in JSFiddle
NB
In any case you should use another name for the function, this is the reason why it doesn't work outside JSFiddle.
I still think it's a duplicate question from here: Can't use "download" as a function name in javascript
And related exclusive on the function name in a tag.
...<a> elements have a download attribute in HTML5 as explained
here...
Maybe a workaround is possible, but definitely not recommendable to mess with browser native functions.
But.. if you still think that it's not.. please try this:
(no hacks needed)
function download() {
alert("hello");
}
function downloadx() {
alert("hello");
}
download <-- not working
<br />
downloadx <-- works
<br />
<span onClick="download();">download</span> <-- works
The last one use download as function name and also work, why?
Because it's not an <a> tag.
I just don't get it. I searched and searched but for this I just can't figure out what's "right".
There are three examples.
1) Fiddle 1.0
Here we have html with onlick="function" and the javascript function right there as well which works fine
<span class="classic one" onclick="someFunction(this,'one')">CLICK HERE</span>
<script type="text/javascript">
function someFunction(obj,nr) {
var string = $(obj).attr('class');
$('.result').text( string );
}
</script>
2) Fiddle 2.0
Then when I move the function to the script section (kind of move it to the .js file) I get an error "ReferenceError: someFunction is not defined"
THIS IS WHERE THE QUESTION BEGINS
3) Fiddle 3
So now I have a function in document ready calling with .on(click which always works fine. This function is calling another function which is outside the docuemnt.ready() and also works fine.
So the question. When do I have to define the functions where AND WHY so it always works?
Thank you!
All the code from Example 3) looks like this:
<div class="result">result</div>
<span class="classic one" onclick="someFunction(this,'one')">CLICK HERE</span>
<span class="classic two" onclick="someFunction(this,'two')">CLICK HERE</span>
<span class="classic three" onclick="someFunction(this,'three')">CLICK HERE</span>
<span class="classic four" onclick="someFunction(this,'four')">CLICK HERE</span>
<div class="ready">ready</div>
<span class="callOtherFunction">Call other function</span>
<script type="text/javascript">
$(document).ready(function(){
$('.ready').text( 'dom is ready' );
function someFunction(obj,nr) {
var string = $(obj).attr('class');
$('.result').text( string );
}
$( "span.callOtherFunction" ).on({
click: function() {
$(this).css("color","red");
$(this).addClass("xyz");
otherFunctionCallingFunction($(this));
}
});
});
function otherFunctionCallingFunction($me) {
$('.callOtherFunction').append( ' --> ' + $me.attr('class') );
}
</script>
A lot of what you're seeing is because of jsFiddle's very surprising default setting, which is to wrap the code in the script pane in an onload handler. So your code is wrapped in a function and no longer at global scope (which is where functions need to be if you use onclick-style attributes). You can change this with the drop-down box on the left (the second one, under the list of libraries and scripts). Change it to "no wrap" to have unwrapped code.
You're not (by far!) the first to be bit by this surprising default.
Answering your main question:
when has a function to be in $(document).ready()
If you control where the script tags loading your script go, you basically never have to use ready; instead, just make sure your script tags are at the end of the HTML, just before the closing </body>.
You can use ready, of course. The reason for doing so is to make sure that all the DOM elements have been created before your code runs. But if you put your script tag at the end, that's already true. You can still define your functions outside of the ready handler (if you want them to be globals), but if you're using ready, you would call them from the ready handler so the elements exist.
FWIW, I would avoid using onclick-style attributes for hooking up event handlers, primarily because they require you to create global functions. I prefer to avoid creating any global symbols when I can avoid it.
The general form I'd recommend:
<!-- ...your page markup here... -->
<script src="any_libraries_you_need_if_you_are_not_combining.js"></script>
<script src="your_script.js"></script>
</body>
</html>
where your script looks like this:
(function($) { // A scoping function that wraps everything
// Hook up event handlers here. You can use `$` for jQuery, even if
// you've used noConflict, because we have a private `$` symbol (see
// the `$` argument above)
// The body of your code goes here
})(jQuery); // <== Note how we're passing the jQuery reference in
// and immediately executing the scoping function
Here's a complete example: Live Copy
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Script Placement Example</title>
</head>
<body>
<input type="button" class="hello-button" value="Click me">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
// This would be in a file, rather than inline
(function($) {
// Hook up handlers
$(".hello-button").click(sayHello);
// Body of the code
function sayHello() {
$("<p>Hello!</p>").appendTo(document.body);
}
})(jQuery);
</script>
</body>
</html>
In JavaScript, scope is handled on a per-function basis. Anything in scope of a function can access other things in scope of that function and things in a wider scope.
Defining a variable with var inside a function will limit the scope of that variable to the function.
Defining a function with a function declaration inside another function will limit the scope of the defined function to the container function.
When you use ready, you pass a function to it. Anything defined in that function is, of course, scoped to that function. Since it is scoped to that function, it is not a global. Your onclick attribute isn't defined in the scope of that function, it can only access globals. This is why you get a reference error.
Avoid globals. They make things hard to maintain. Avoid onclick attributes, they usually depend on globals.
You need to use ready if you want code to run after the DOM has been fully constructed. This is useful if you want to bind event handlers to elements in it with JS (e.g. with jQuery.on). Do this rather then using onclick attributes.
I've got my fiddle here, but I can't understand why it's not calling my function on the 'onmouseout' event.
http://jsfiddle.net/foreyez/Xf6LW/
any ideas?
Works fine, you just needed to put the function in the head (or body after the element is in the DOM) of the document.
jsFiddle example
It's because the functions you create in the JavaScript panel are not global when you have the onLoad option selected. Your JavaScript gets wrapped in a function.
If you do want them to be global you have to either do what j08961 suggested, by changing that dropdown to say no wrap (body or head) will work
The best solution would be to not set your event handlers from HTML, that's bad practice anyway, then you're not relying on global functions or mixing HTML and JS.
<div id="myDiv">
</div>
document.getElementById('myDiv').onmousemove = function() {
alert('here');
}
Side note: you should have noticed the error in the console saying that myFunc is undefined or something like it.
I think it's cause for jsfiddle, it declares all the javascript AFTER the HTML. The HTML is going to run and look for a myFunc and not find it. Then it's going to load the JS and it won't even run it.
Here you can see the changes : jsfiddle.
make myFunc as a global function;
I searched my code using firebug and got following generated code.
window.addEvent('load', function() {
//window.myFunc makes myFunc as a global function
// It can be accessed from any were inside current window.
window.myFunc = function myFunc(x)
{
alert('yo');
}
// function below is not available gloably.
function myFunct1(){
alert('yo1');
}
});
see jsfiddle
here is the problem..
i have a javascript file which is named javascript.js like this
$(document).ready(function(){
function init()
{
//code goes here
}
}
now the index.html file has a command button which should call the init() function.
<html>
<head><script src=javascript.js ....></script>
<body><button type="button" onclick="init()">Call Init!</button></body>
</html>
But it doesn't call it. Nothing happens as expected. Please suggest a solution.
You should define your function outside $(document).ready() scope.
The onclick attribute will be executed in a global context. Your init function is scoped to the anonymous function which you pass to jQuery. Three solutions:
Move the init function outside of the ready function, into the global scope
export the init function by making it a property of the global object: window.init = function() {…};
as you use jQuery, you should not need to define any handlers in attributes. Instead use (inside the ready function): $("button").click(function init() {…}); Even better use an id to reference the button.
Try viewing the page in chrome. Hit F12 to view the console. You'll be able to quickly debug the issue. At first glance, however, I do see that your $(document).ready function is not closed properly. Add ');' at the end of the code you included. Also, add quotes around javascript.js in your script tag. See if that helps.
Why don't you use
function init()
{
$(document).ready(function() {
//code goes here
});
}
You can use flag too in order to keep track if the "//code goes here" proceeded or not. So in case of document not ready yet, you can use while loop with setTimeOut function for some pause interval "In order to not hang the client browser".
In my HTML-head i have this script included:
<script id="mode" type="text/javascript" src="article.js"></script>
With a button click I'd like to change the source of the script to customers.js so that it then looks like this:
<script id="mode" type="text/javascript" src="customers.js"></script>
The point is that I don't want the article.js to be included in my page then anymore, so I can't just use .append().
So, click on the article button -> only article.js included, click on the customers button -> only customers.js included.
I tried to solve this with jQuery this way, but I doesn' seem to work...:
$("#btArticle").click(function(){
$("#mode").attr("src","article.js");
});
$("#btCustomers").click(function(){
$("#mode").attr("src","customers.js");
});
Do you know where my mistake is?
Update: There are methods with the same name in customers.js and article.js. So there's a onSave() method in both of them and when I clicked the customer button before, I want the onSave() method of customers.js to be executed, not the one in articles.js.
The point is that I don't want the article.js to be included in my page then anymore, so I can't just use .append().
Once the script has been downloaded and evaluated, anything it leaves lying around will remain unless explicitly removed; they're not linked to the script element itself and removing it won't have any effect on them.
The only way to get rid of the stuff article.js leaves lying around is to remove or overwrite each and every thing it creates and keeps.
Concrete example:
// article.js
var foo = "bar";
jQuery(function($) {
$(".stuff").click(function() {
alert("You clicked stuff!");
});
});
If the article.js listed above is processed, you can remove the script element that loaded it, and that will have no effect on the foo global variable or the event handler that it hooked up.
If you want to have scripts that you can unload, have them use the module pattern with a single global symbol they add by assigning to a property on window, e.g.:
// article.js
window.articleScript = (function() {
var foo = "bar";
jQuery(function($) {
$(".stuff").bind("click.article", function() {
alert("You clicked stuff!");
});
});
function remove() {
$(".stuff").unbind("click.article");
try {
delete window.articleScript;
}
catch (e) { // Early IEs throw incorrectly on the above
window.articleScript = undefined;
}
}
return {
remove: remove
};
})();
You can then remove it by doing this:
articleScript.remove();
Re your comment on the question:
Maybe I should've mentioned that there are methods in both files with the same name.
If you have global function declarations in customers.js that use the same name as global function declarations in articles.js, when you load customers.js, it will replace those functions.
So if you have this in articles.js:
function foo() {
alert("Articles!");
}
...and this in customers.js:
function foo() {
alert("Customers!");
}
And you have a button:
<input type="button" onclick="foo();" value="Foo">
When you've loaded just articles.js and not customers.js, clicking that button gives you "Articles!". If you then load customers.js, clicking the button will give you "Customers!".
That works because the event handler calls foo(), but the event handler itself is not foo. The onclick attribute creates a hidden event handler for you. The equivalent jQuery would be:
$("input[type='button'][value='Foo']").click(function() {
foo();
});
Note that just doing .click(foo) will do something very different: It will hook up the function that foo points to at that moment as the event handler. Even if you change what foo points to later (by loading customers.js), that won't change the fact that the old function is hooked up as a handler.
FWIW, from the question and your comments, I think I'd recommend sitting back and reviewing your strategy for this page/app. All of this swapping of code in and out and such seems like a design problem.
You are not actually loading and running the respective scripts, you are just changing the source for that tag. Use .getScript() to load and run the appropriate JavaScript file:
http://api.jquery.com/jQuery.getScript/