click event occurs with onload event [duplicate] - javascript

I playing around with a function that I want to bind to all the links. At the present the function fires when the page loads, instead of when I click on the link.
Here's my code. (I can post the function showDiv(), if you need to see it.) Can you tell if I'm doing something wrong or stupid here?
$(document).ready(function(){
$('a.test').bind("click", showDiv());
});
Thanks!

You want to pass a reference to a function as a callback, and not the result of function execution:
showDiv() returns some value; if no return statement was used, undefined is returned.
showDiv is a reference to the function that should be executed.
This should work:
$(document).ready(function() {
$('a.test').on("click", showDiv); // jQuery 1.7 and higher
$('a.test').bind("click", showDiv); // jQuery 1.6 and lower
});
Alternatively, you could use an anonymous function to perform a more advanced function:
// jQuery 1.7 and higher
el.on('click', function() {
foo.showDiv(a, b, c);
// more code...
});
// jQuery 1.6 and lower
el.bind('click', function() {
foo.showDiv(a, b, c);
// more code...
});
In some circumstances you may want to use the value returned by a function as a callback:
function function foo(which) {
function bar() {
console.log('so very true');
}
function baz() {
console.log('no way!');
}
return which ? bar : baz;
}
el.click(foo(fizz));
In this example, foo is evaluated using fizz and returns a function that will be assigned as the callback for the click event.

Looks like you're calling the function showDiv directly there (and binding the return result of showDiv() to the click handler instead of binding it directly.
You want something like
$(document).ready(function() { $('a.test').bind("click", showDiv); });

Use the below line. showDiv() will call the function rigth away when that line is executed.
$('a.test').bind("click", showDiv);

Change it to: $('a.test').bind("click", showDiv); (do not put parens around showDiv since you want to pass the function reference).

Related

Why my function with sending message from popup.js to content.js is executed immediately when clicking on extension? [duplicate]

I playing around with a function that I want to bind to all the links. At the present the function fires when the page loads, instead of when I click on the link.
Here's my code. (I can post the function showDiv(), if you need to see it.) Can you tell if I'm doing something wrong or stupid here?
$(document).ready(function(){
$('a.test').bind("click", showDiv());
});
Thanks!
You want to pass a reference to a function as a callback, and not the result of function execution:
showDiv() returns some value; if no return statement was used, undefined is returned.
showDiv is a reference to the function that should be executed.
This should work:
$(document).ready(function() {
$('a.test').on("click", showDiv); // jQuery 1.7 and higher
$('a.test').bind("click", showDiv); // jQuery 1.6 and lower
});
Alternatively, you could use an anonymous function to perform a more advanced function:
// jQuery 1.7 and higher
el.on('click', function() {
foo.showDiv(a, b, c);
// more code...
});
// jQuery 1.6 and lower
el.bind('click', function() {
foo.showDiv(a, b, c);
// more code...
});
In some circumstances you may want to use the value returned by a function as a callback:
function function foo(which) {
function bar() {
console.log('so very true');
}
function baz() {
console.log('no way!');
}
return which ? bar : baz;
}
el.click(foo(fizz));
In this example, foo is evaluated using fizz and returns a function that will be assigned as the callback for the click event.
Looks like you're calling the function showDiv directly there (and binding the return result of showDiv() to the click handler instead of binding it directly.
You want something like
$(document).ready(function() { $('a.test').bind("click", showDiv); });
Use the below line. showDiv() will call the function rigth away when that line is executed.
$('a.test').bind("click", showDiv);
Change it to: $('a.test').bind("click", showDiv); (do not put parens around showDiv since you want to pass the function reference).

Self Invoking Function as jQuery ducument ready callback

What is the difference between
$(function() {
// bind some event listeners
});
and
$(function() {
// bind some event listeners
}());
$(function() {
// bind some event listeners
});
In above case the function is passed to the jquery which will get executed once document is ready.
$(function() {
// bind some event listeners
}());
In above case the return of the function is passed to the jquery.
Since the function is se3lf executing itself, it will get executed immediately and whatever the function returns will get passed to the jquery, so this is not a good way because the objective is to execute the function once document gets ready which is not happening in this case
$(function(){...}); OR $(document).ready(function(){ ... });
This Function is called when the DOM is ready which means, you can start to query elements for instance. .ready() will use different ways on different browsers to make sure that the DOM really IS ready.
(function(){ ... })();
That is nothing else than a function that invokes itself as soon as possible when the browser is interpreting your JavaScript. Therefore, its very unlikely that you can successfully act on DOM elements here.
$(function() { ... });
is just jQuery short-hand for:
$(document).ready(function() { ... });
Immediately-invoked function expression (or IIFE), instead, are expression
"immediately executed", the convention is to enclose in parentheses, but every kind of expression is executed immediately, see following IIFE functions:
(function() {
console.log("IIFE 1");
}());
+function() {
console.log("IIFE 2");
}();
1-function() {
console.log("IIFE 3");
}();
var f = 50 * function() {
console.log("IIFE 4");
}();
I hope it was clear, bye.
$(function() {
// bind some event listeners
});
This one will be executed only when the DOM is fully loaded, it's the shortcut for :
$(document).ready(function(){
// Write code here
});
$(function() {
// bind some event listeners
}());
This one is the same but the function inside the $() is a self invoking function. Usually the goal is to prevent variable name conflicts, because it's creating a new scope.

Function does not work in Javascript

i have this function in jQuery:
$(document).ready(function(){ function MyFunction() {alert('Hello!');} });
(For example only)
but, i'm want call this function with regular Javscript this way:
if(x == y){MyFunction();}
(For example only)
and i'ts not work.
However, When i try it:
function MyFunction(){alert('Hello!');} if(x == y){MyFunction();}
(Without jQuery function)
it's work.
Why?
if you put the function outside of the .ready() and call it in the ready function it will work, if you put it in the ready() and call it outside of ready it will give you an error you may have a function declared outside of ready state using jQuery code and call it inside.
function MyFunction(){
alert("hello!!");
}
//on ready
$(document).ready(function(){
if(x==y)
MyFunction();
});
I understand your issue like this {but not really clear what you are looking for imho}
Define function:
function MyFunction(){alert('Hello!');}
Call it on document ready:
$(MyFunction);
Now whenever you want, you could use:
if(x == y){MyFunction();}
this line:
if(x == y){MyFunction();}
should also be in the document.ready statement.
if you call it outside it will run before the function was actually defined and thus it will fail.
Lesonchi has it right. The issue is 'scope'.
The $(document).ready(...) call takes a function which is it's own scope (Javascript only has function scoping). So, anything defined inside the function you are passing to that call is ONLY available inside that function.
Based on your question, I assume you wanted to be able to call that MyFunction method elsewhere in the code and not just in the $(document).ready() - so, defining it outside the that call would give it 'global' scope, and hence could be used elsewhere in your code:
function MyFunction(){ /* do something */ }
$(document).ready(function(){
MyFunction(); // call it in this scope
});
// call it in 'global' scope
if (x == y) {
MyFunction();
}
See Also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope

Using jquery how to call a function and call another function from the previous when function execution is completed

I have to perform a task based on jquery. When the page loads, the first jquery function will be called. Once the first function completes successfully, then it should automatically call the next function.
Here is a working demo JSFIDDLE
JS:
function func_one()
{
alert('func_one');
alert('Now call func_two');
func_two();
}
function func_two()
{
alert('func_two');
}
//jquery Function block that will be executed on page load
$(document).ready(function(){
//call the function one
func_one();
});
If the function is actually a function then just call it functionA() as per good ol' JavaScript. If it is an event then use Jquery trigger see http://api.jquery.com/trigger/
if it is possible then chaining the functions might also be a good idea.as in FunctionA().FunctionB();
you can 'pass' callback function to other functions. see example:
function one(callback) {
// do stuff ...
// do stuff ...
// do stuff ...
if (typeof(callback) === 'function')
callback();
}
function two() {
}
now, declare document ready and call function one. when it completes, we'll call function two.
$(document).ready(function(){
one(function(){
// code after 'one' ended
two();
});
});
that's the general idea. hope that helps.

Why is function() needed sometimes in JavaScript?

HTML
<button id='hello'>Click Me!</button>
JavaScript (wrong)
$('#hello').click(alert('Hello, World!'));
JavaScript (correct)
$('#hello').click(function() {
alert('Hello, World!');
}
I'm wondering why the first JS code triggers on the event load instead of click. Can anyone tell me why function() { [code] } is needed for the script to work properly?
In this example, I used jQuery events, but this is not specific to it, for example, I need to use it with setTimeout, too.
The click function expects another function as a parameter.
In the first case you would be passing the result of calling alert('hello world');, which is null.
The second is just a shorthand for:
$('#hello').click(callback);
function callback(){
alert('hello world');
}
Because .click() is a handler. The first argument is a function to assign. But if you actually pass the function with arguments then it will call the function (in this case alert) and then pass it's return value.
Writing $('#hello).click( function() { } )` is basically a short hand for writing:
var myfunction = function() {
// code
};
$('#hello').click( myfunction );
As you can see in the long hand way, it's passed as a reference to the function instead of the function's return value.
Your first example says "evaluate
alert('Hello, World!')
right now, and pass the result as an argument to click. "
The second says "Define a function which will do the alert when I call it, and pass that whole function as an argument to click.
The function() { ... } syntax is how you declare an anonymous function in Javascript. jQuery uses lots of these to specify that some action will be performed later, like when an event occurs. You can think of it as delaying the execution of your function until necessary. Without this syntax, whatever code you place there is evaluated immediately, which is not what you want for an event handler.
You might think, "why isn't JavaScript smart enough to know the difference?" Consider this:
function returnCallback(linkId, data) {
return function(e) {
alert('Clicked on ' + linkId + '. Here is some data: ' + data);
// Maybe do some stuff with e, the event parameter
}
}
$('#some-link').click(returnCallback('some-link', 'some-data'));
$('#other-link').click(returnCallback('other-link', 'different-data'));
This is a contrived example, but it illustrates the power of anonymous functions and closures. This works since returnCallback returns a function.
In the first instance, "JavaScript wrong", you're actually calling alert('Hello, World!') at the point that the script is loaded. Now, the reason you pass the .click function a function is because it can call it at any point. Essentially, you're packing code together to be run (or not run at all) at any point when you put it in a function.
$('#hello').click(alert('Hello, World!')); is attempting to run alert('...') and pass its return value to the .click() function which will not work as expected.
This is because JavaScript evaluates everything and during this process your alert is invoked. You can use anonymous function or you can also use your own custom function as implemented below:
<script language="javascript" type="text/javascript">
$("#mybutton").click(clickFired);
function clickFired() {
alert('click fired');
}
</script>
The parameter required for the .click() function is a Function. Therefore $("#hello").click(function { [code] }); is required. Because there's nothing to return by alert().
The click function here assigns a value to the event handler.
With the first ("wrong") code you're assigning a value of alert('Hello, World!') which is itself a function call, so it's going to be immediately evaluated and hence appear at load.
With the second ("correct") code you're now assigning a new anonymous function which is not executed itself, just instantiated at load. Hence this will work as expected later.
somefunction(alert('hello! world'));
this would mean you want to pass to somefunction the return value of alert("hello! world").
jquery click expects a callback that it should fire upon click on the element. so you put it in a function which does not execute unless someone (here jquery) calls it explicitly.

Categories