javascript function does not work within jquery $(document).ready block - javascript

I am trying to call a JavaScript function from an onclick trigger.
HTML section:
<div class="my_radio">
<input type="radio" name="my_radio" value="1" onclick="my_func()"/> first button
</div><!-- end of class my_radio -->
And the JavaScript code
<script type="text/javascript">
$(document).ready(function(){
function my_func(){
alert("this is an alert");
}
});
</script>
It does not work.
But if i keep the JavaScript function out of the $(document).ready() code, it works. Following is the relevant code snippet:
<script type="text/javascript">
$(document).ready(function(){
function my_func111(){
alert("this is an alert");
}
});
function my_func(){
alert("this is an alert");
}
</script>
1) Why does not the first JavaScript code snippet work?
2) How can I get the first JavaScript code snippet working ?
EDIT :
SO FAR AS I KNOW, $(document).ready() is executed when the web page loads completely. So how can I prevent my_func() to be active before or after the complete page-loading if I write my_func() outside $(document).ready()?

It's all about javascript execution contexts and scope.
Everything that you define within a function is know only in this function.
In your first test, the function my_func() can only be used within the ready callback (and in the inner other objects). You can't reference it outside.
In your second example, the function my_func() is global to the document and accessible from anywhere.
I recognize this is maybe a verry simple explanation :-)

If you define your function within a callback, you can only use it within this callback:
$(document).ready(function(){
function something(){
alert('test');
}
//..
something(); // Will work
}
something(); // Won't work

Your first snippet doesn't work, because in in the function my_func111 is defined within the local scope of an anonymous function passed as an argument in your $(document).ready call.
You can fix your code by placing the function definition to the document scope and calling it inside ready function such as:
function my_func(){
alert("this is an alert");
}
$(document).ready(function(){
my_func();
});

I presume by "it does not work", you mean it says "my_func is not defined" or similar?
When you define a function within a function, the inner function is not visible outside of the outer function (unless it is part of the outer function's return statement).
You'll need to learn about closures, a good tutorial on which can be found here.

You'll add a global variable isReady. The $(document).ready callback section will change it to true.
Both your function and the isReady variable must be defined outside the callback of the $(document).ready, so that they can be seen from outside the scope of the callback.
<script type="text/javascript">
var isReady = false; // outside the onReady callback
function myFunc(){ // also outside the onReady callback
if (!isReady) return; // abort if not ready
alert("this is an alert");
}
// the onReady callback
$(function(){ // the newer jquery shorthand for: (document).ready(function(){
isReady = true;
});
</script>
Your HTML code needs no changes. - I changed the names to use JS and HTML conventions, but essentially it's the same as what you originally wrote...
<div class="divMyRadio">
<input type="radio" id="myRadio" value="1" onclick="myFunc()"/> first button
</div><!-- end of class divMyRadio -->
I
As a side note: The newer JQuery uses $(function(){ as shorthand for $(document).ready(function(){ to make things easier for you.

Related

execute jQuery on calling some function

I want to perform some task in jQuery when some other function in my JavaScript is called.
To explain the question: Let's say I have function foo(){..} in JavaScript.
While my code is under execution phase, I want to perform some action using jQuery whenever function foo(){..} is called.
Rough Demo:
<!DOCTYPE html>
<title>Demo</title>
<body>
<script>
function foo()
{
alert("Function Called");
}
...Some code....
if(some condition)
foo(); //function Call - I want to execute jQuery event when this line is executed.
else
woo();
</script>
</body>
</html>
Is there any event handler which can achieve this?
After seeing the updated question, the only way to handle this would be to put your jquery function at the same level as function foo() and call it from there as explained in this example.

trouble with jQuery lifecycle

index.html:
<input type="text" id="inputs" name="inputs">
<input type="button" id="btnAdd" value="submit">
script.js:
(function() {
function myFunction(input) {
alert(input);
}
$('#btnAdd').click(myFunction($('#inputs').val()));
});
I'm having trouble getting my javascript to run when my button is clicked. I assume I am misusing the ready function or my page has yet to register the button, but I am unable to break at any linein the javascript when I debug the page. Can someone tell me the proper way to get this to function? Thanks.
Because of the way it's written, the code you provide for script.js would never run. You probably want to put your function into a call to jQuery so it gets executed when the DOM is loaded.
Also, you need to wrap your click callback inside an anonymous function, or else it will execute myFunction when you're trying to add the callback instead of on the actual click.
$(function() {
function myFunction(input) {
alert(input);
}
$('#btnAdd').click(function() {
myFunction($('#inputs').val())
});
});
https://jsfiddle.net/9du8rxw0/
you need to add callback to your click event and for $(document).ready(function(){ }) the short hand is $(function(){ }).and it is better to write custom functions outside of document ready.
$(function() {
$('#btnAdd').click(function() {
myFunction($('#inputs').val())
});
});
function myFunction(data) {
alert(data);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inputs" name="inputs">
<input type="button" id="btnAdd" value="submit">
Adding a $ before your self-invoking function will tell jQuery to wait for the entire page, including your myFunction definition to load prior to execution.
like
$(function() {
function myFunction(input) {
alert(input);
}
$('#btnAdd').click(myFunction($('#inputs').val()));
});
then make sure either myFunction is declared in global scope, or better yet, wrap within your self-invoking function as well.
You need the $ in front of (function(), and your click function needs curly braces.
$(function() {
function myFunction(input) {
alert(input);
}
$('#btnAdd').click(function(){myFunction($('#inputs').val())});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="text" id="inputs" name="inputs">
<input type="button" id="btnAdd" value="submit">
I'm guessing that the DOM is not yet loaded, and that your attempt to shorthand the call to .ready() is erroneous. Try prefixing with $:
Also, your event handler setup is not doing what you want.
// Need $ before your parens (shorthand for .ready())
$(function() {
function myFunction(eventData) {
alert(eventData.inputValue); // <-- get input value from eventData
}
// This is not proper usage of .click()
// https://api.jquery.com/click/
// $('#btnAdd').click(myFunction($('#inputs').val()));
// You want to pass the relevant eventData as the first param,
// and a reference to your handler in the second.
$('#btnAdd').click( { inputValue: $('#inputs').val() }, myFunction);
});
Although, if you don't need myFunction to be defined separately, you might be better off with #Gerasimos' suggestion.

jQuery ready block hiding code outline in IDE

When I write the following code, whether Im using Aptana, Dreamweaver or Eclipse, I can never see functions in the onready block in the outline view:
$(document).ready(function(){
function myFunction(){
}
function myFunction2(){
}
});
Basically the only thing I see in outline is the onready and I have to remove the onready if I want to see all my functions. What technique or way of handling this situation can I try to both see all the functions in outline view and still use onready?
What technique or way of handling this situation can I try to both see
all the functions in outline view and still use onready?
Just don't define your own functions inside like you demostrated. It's unnecessary. Have your functions defined outside like so:
function myFunction(){
}
function myFunction2(){
}
$(document).ready(function() {
myFunction();
myFunction2();
});
A simpler way to do the onready is:
$(function(){
... code here ...
})
Maybe this will solve your problem...

Trying to pass in a callback function fails

I am trying to create some functionality when a user clicks on an element on the webpage. The callback function executes as soon as the page is executed. It is only supposed to execute when the user clicks on an element.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Javascript Test</title>
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script>
$("#clickMe").one('click', printThis("Hello All"));
function printThis(msg) {
console.log(msg);
}
</script>
</head>
<body>
<div id="clickMe">Click me!</div>
</body>
</html>
Thanks!
That isn't actually passing the function, but instead it is evaluating the function and passing the result as the callback parameter (in this case, undefined).
Try this instead
<script>
function printThis(msg) {
console.log(msg);
}
$("#clickMe").one('click', function() {
printThis("Hello All");
});
</script>
Don't invoke the callback. Pass an anonymous callback function that invokes the function you want.
function printThis(msg) {
console.log(msg);
}
$("#clickMe").one('click', function() { printThis("Hello All") });
one method takes a callback as the second parameter. printThis("Hello All") will actually call the method there itself so on click of clickMe nothing will happen as there is no handler attached. Try this
function printThis(msg) {
console.log(msg);
}
$("#clickMe").one('click', function() { printThis("Hello All") });
The answer already posted is right:
$("#clickMe").one('click', function() { printThis("Hello All") });
This is known as a closure: https://developer.mozilla.org/en/JavaScript/Guide/Closures
A closure is a function, often declared as an inline/anonymous block of code, that delays the execution of your function and stores the value of that "Hello All" argument that you want to pass in.
jQuery will store this "function() {...}" code block as an event handler, and then later when the #clickMe element is clicked, that code block will be executed, which in turn will call the printThis function.
You will find yourself using this pattern quite often with jQuery.
Try this ... http://jsfiddle.net/PcVJq/

Why can't I use onClick to execute a function inside a jQuery $(document).ready function?

I'm new to JavaScript and jQuery. I want to click a button and have a js function executed. (For this example, it's just an alert, but it's actually an ajax function.)
The first alert appears, but after I click the button, I never see the second ("did it") alert. It looks like JavaScript doesn't think the doIt() function is defined when the button is clicked.
Here's the relevant code:
$(document).ready(function()
{
alert('ready');
function doIt() {
alert('did it');
};
}
)
<body>
<input name="Go" type="button" value="Go" onclick="doIt();"/>
</body>
It's because that function isn't in a global context, which is where your onclick="" is looking for it. You need to move it outside your document.ready (so it's not scoped exclusively to that closure), or (a better approach IMO) bind it inside the document.ready, here's what I mean by each:
Binding it inside (remove your onclick="" for this):
$(document).ready(function() {
alert('ready');
$("input[name='Go']").click(doIt);
function doIt() {
alert('did it');
}
});
or the anonymous version (again remove your onclick=""):
$(document).ready(function() {
alert('ready');
$("input[name='Go']").click(function() {
alert('did it');
});
});
Or move it outside (keep your onclick=""):
$(document).ready(function() {
alert('ready');
});
function doIt() {
alert('did it');
}
You define doIt in your document.ready as a function statement.
Either you should use a function expression
or declare the function out of the ready function.
$(document).ready(function()
{
alert('ready');
doIt = function() { //now has global scope.
alert('did it');
};
}
)
<body>
<input name="Go" type="button" value="Go" onclick="doIt();"/>
</body>
(yes, the onClick is not really the jQuery way of doing it and probably should be replaced by a click handler defined in the ready function, but it works and is allowed.
What you need to do is bind a "click" event to it using jquery like this.
jQuery(document).ready(function($) {
$('#my_button').click(function() {
alert('i was clicked');
});
});
<input type="button" id="my_button" value="Go" />
Here is a live jsfiddle demo for you: http://jsfiddle.net/8A5PR/
Here is the manual page for you: http://api.jquery.com/click/
Javascript has two kinds of scope, global, and function level. If you declare doIt inside a function, it will not be visible outside the function. There are a few ways to fix it
//just declare the function outside the ready function
$(function() {
});
function doIt() { alert('did it'); }
//decare a variable outside the function
var doIt;
$(function() {
doIt = function() { alert('did it'); }
});
// if you dont use var, variables are global
$(function() {
doIt = function() { alert('did it'); }
})
$(document).ready(function()
{
});
is an event handler for document.ready, the functions inside that handler are within that scope.
A better method is to insert a handler for your click event inside, then call that function there.
$(document).ready(function()
{
alert('ready');
$('body input').click(function(){
doIt();
});
function doIt() {
alert('did it');
};
});
This ALSO has the side effect of removing code from your markup (a good thing) in that you can remove that onclick from your input tag.
What you are doing right now is simply putting a function doIt() inside a (for all intents and purposes) window.onload event. This function will never get called outside of the document.ready unless you bind it to an element because it's stuck inside the scope of document.ready.
You need to move your function outside of the document.ready so it can be called by outside events.
Just a little link for reference: http://www.webdevelopersnotes.com/tutorials/javascript/global_local_variables_scope_javascript.php3
Try this...
$(document).ready(function() {
alert('ready');
$("#Go").submit(function(event) {
alert('did it');
});
});
<input name="Go" id="Go" type="button" value="Go" />
Yes, as mentioned by others you really need to move the function outside of the jquery ready declaration. Also please note that javascript is case sensitive, hence you should use onClick rather than onclick. Regards

Categories