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/
Related
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.
I wrote a sample jQuery program and found that the function triclick() is called during the document load by jQuery.
If I replace the part1 by part2, then the click() function is working fine. Please clarify on where I am wrong?
I want the element H2 disappear on click of H3. But the element H2 hides on load itself.
Part 1:
$(document).ready(function()
{
$("h1").hide();
$("h3").click(triclick());
});
function triclick()
{
$("h2").hide();
alert('H2 is hidden');
}
Part 2: Works fine on click of
$(document).ready(function()
{
$("h1").hide();
$("h3").click(function()
{
$("h2").hide();
alert('H2 is hidden');
});
});
The complete program:
You've two pass your function inside a anonymous function:
$(document).ready(function() {
$("h1").hide();
$("h3").click(function(){triclick()});
});
Or just:
$(document).ready(function() {
$("h1").hide();
$("h3").click(triclick);
});
Yous should only pass the reference to the function to the click and not call the function.
you need to pass only name of function. () <- means to execute it
$(document).ready(function() {
$("h1").hide();
$("h3").click(triclick);
});
the problem is
$("h3").click(triclick());
this means ,when "h3" is clicked it will run the result be returned by the function "triclick"
but here you should transfer the parameter the function name ,not the function executed-result;
you should know the parentheses is an operator in javascript ,when it follow the defined function name ,it will have the function executed in an function expression.
change the code to
$(document).ready(function() {
$("h1").hide();
$("h3").click(triclick);
});
when "h3" is clicked the function triclick will run
So i have the following jQuery:
<script type="text/javascript">
// Init.
$(function () {
// Wire up the search box.
$('#searchButton').click(
search($('#query').val(),
$('aaa').val(),
$('bbb').val()
));
});
</script>
But when i first hit the page, the search function is getting fired (because I put a breakpoint in there).
I thought my code (above) is just saying: Wire up the click event AND when someone clicks that button, the following code is called => search function with the following 3 arguments).
Can anyone tell me what I've done wrong, please?
Because it expects a function reference. What you're doing is executing search() and passing that result as the reference.
<script type="text/javascript">
// Init.
$(function () {
// Wire up the search box.
$('#searchButton').click(function() {
search($('#query').val(),
$('aaa').val(),
$('bbb').val()
));
}
});
</script>
You should wrap your handler code inside an anonymous function.
Otherwise search() will get evaluated and the result will be applied to the click handler.
Try this:
$(function () {
$('#searchButton').click(function () {
search( $('#query').val(),
$('aaa').val(),
$('bbb').val()
);
});
});
Because you are calling function "click" with one parameter, the return of "search(); and it is not a function callback.
How about this?
<script type="text/javascript">
// Init.
$(function () {
// Wire up the search box.
$('#searchButton').click(function() {
search($('#query').val(),
$('aaa').val(),
$('bbb').val()); }
);
});
</script>
Attach anonymous function on click event,
and call search($('#query').val(),$('aaa').val(),$('bbb').val()); in function.
$('#searchButton').live('click',function() {
whatever...
});
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.
THis is what I want.
onclick="pager(function2();)
but it doesn't seem to work.
Take out the semicolon:
onclick="pager(function2())"
http://jsfiddle.net/BQYVV/
You are not passing a function to a function, but just a value. When the element is clicked, function2() is called, and it's return value becomes an argument to the pager() function. If function2 does not return anything, pager will receive undefined as an argument.
This works for me
<html>
<head>
</head>
<body>
Click me
<script>
function function2(msg) { alert(msg); };
function function1() { return "Hello World"; };
</script>
</body>
</html>
What's not working in your code?
you can do something like this to make it work
<p onclick="pager(function2())">Click Me</p>
function pager(fn){
return fn;
}
function function2(){
alert('hello');
}
If you're using jQuery, please don't use in-line script, assign the click handler, like this:
$("div").click(function() {
pager(function2());
});
This is if you wanted to assign it to all <div> elements, if you wanted it on a particular element via ID, like this: Link. You would use $("#bob") instead of $("div"). There's a full list of selectors here, if you're familiar with CSS, you'll feel right at home.