calling javascript function from html doesn't work - javascript

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".

Related

Calling Javascript function from external file when loading html page

I want to load a function named james() from a Javascript file named hello.js which is added as an external file to index.html.
My problem is when the function james is declared inside $(document).ready(function()), it just says that 'james function is undefined' and is not called. How can I call function declared inside document.ready using onload?
<html>
<head>
</head>
<body onload= "james()">
<script src=hello.js>
</body>
</html>
hello.js javascript file
function mountApp{
$(document).ready(function(){
function james(){
alert("how can i get call ,when html page is loaded");
}
});
}
true method is, you create function outside document.ready function and then call
function james()
{
alert("how can i get call ,when html page is loaded");
}
$(document).ready(function(){
james();
)};
Your "james" function does not exist in the correct scope. It is declared inside the "ready" event listener and only exists inside the listener scope. After that, it won't be available anymore.
You cannot do what you are trying to do. Functions cannot be used outside of the scope they were declared in.
Move the function to the global scope instead.
function mountApp{
$(document).ready(function(){
// You can call the function from here
james();
});
}
function james(){
alert("how can i get call ,when html page is loaded");
}
Now, I don't see why you would be adding an event listener "onready" inside a function, because function calls will only be executed after the DOM is ready, so it will never trigger.

Mouse Events on JsFiddle not working?

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

Change JavaScript and delete old one

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/

AS3 navigateToURL(); javascript function not firing when using jQuery

I have a problem I cannot seem to solve. I am using AS3's navigateToURL(); function to call a simple javascript function. At the moment it just alerts the first parameter. The problem is, when this function is placed inside of the $(document).ready(function(){..}) block it does not fire. Example of my code:
<script type="text/javascript">
$(document).ready(function(){
function mapLink(aVar){
alert(aVar);
};
});
</script>
Example of simple AS3 call to function:
navigateToURL(new URLRequest('Javascript: mapLink("'+mapObject.tooltipMoreLink+'");'), '_self');
When the function is placed OUTSIDE of the jquery code, it works fine. Why does it need to be inside of the jquery code you may be asking? I need the jQuery DOM selectors to manipulate certain dom elements based on the value of 'aVar' in my javascript function.
Any guidance is welcomed with an open mind.
eh. this is what the ExternalInterface class was designed for.
You issue has to do with scope. Your function is scoped to the jquery object, and not globally, so it is invisible to your call. If you need jquery selectors, then you could easily set the flash var independently, followed by the jquery routine.
update
maybe I'm missing something, but shouldn't this be as be easy as:
function externalCall(param){
$(domElement).doSomething(param);
}
?
I wouldn't think this need be tied to the jq ready function. I mean, if flash has already loaded, and the user is interacting, then certainly the ready event has long since fired successfully.
Hope that helps. I'm not sure I'm following exactly what you're trying to do ;)
...
btw - I really would look into ExternalInterface, NavToURL may work, but you can call your js directly with the former method.
It won't work because you have created a function inside the DOMReady Event
that is $(document).ready and calling it from outside the scope of the function.
You can access jQuery DOM Selectors from anywhere provided you have referenced jQuery.js in your page.
Example
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript">
function mapLink(aVar){
alert(aVar);
}
</script>

Why isn't my JavaScript working in JSFiddle?

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");
}

Categories

Resources