Can someone explain me like i'm five why is it executing the function without the click event. And how to fix it. Thanks.
function test(){
alert("works");
}
function createButton(name,location,id,funX){
var button = document.createElement("input");
button.type = "submit";
button.name = name;
button.id = id;
button.onclick = funX;
var placeHolder = document.getElementById(location);
placeHolder.appendChild(button);
};
window.onload = function () {
createButton("Submit","content","submitEnd",test());
};
http://jsfiddle.net/mabui91/yLoty39s/
When you add parenthesis to a function, you call it. Not later, but right then and there, and you return what ever the function returns.
A function in javascript returns undefined by default, unless you explicitly return something else.
What you're really writing is
createButton("Submit", "content", "submitEnd", undefined);
The last undefined is because you called the function, it would be the same as
var result = test(); // undefined
createButton("Submit", "content", "submitEnd", result);
The way to solve it, is to reference the function, not call it
createButton("Submit", "content", "submitEnd", test);
See, no parenthesis.
FIDDLE
Related
I don't know how to ask this on google that's why I asked here instead,
The console.log from the getListByElement() function won't execute here,
I am modifying a very large existing project and uses functionality hooks for validation purposes and executes that hook on certain .on events, what I want to know is why the console.log won't get executed,
which gets executed first,
Order of execution on my understanding
1. trigger event function for the field `fieldName`
2. fieldName.functionalityHook = [Apple.functionalityHook()];
3. Apple.functionalityHook = function(func) {
4. return function(e) {
5. getListByElement(ele); and display console.log();
6. return func;
Here is the sample code that I have,
var Apple= window.Apple; // global
fieldName.functionalityHook = [Apple.functionalityHook()];
Apple.functionalityHook = function(func) {
return function(e) {
var ele = $(e.target);
getListByElement(ele);
return func;
}
}
function getListByElement(ele){
console.log('ele here');
}
Thank You for answering,
as par my understanding your getListByElement() is not invoking because of the function initialization. You are calling the functionalityHook() before its initialization.
fieldName.functionalityHook = [Apple.functionalityHook()];
Apple.functionalityHook = function(func) {..........
and this invocation returning a function
return function(e) {
var ele = $(e.target);
getListByElement(ele);
return func;
}
and inside this function getListByElement() is calling.
So, the correct code arrangement should be like this.
var Apple= window.Apple;
function getListByElement(ele){
console.log('ele here');
}
Apple.functionalityHook = function(func) {
return function(e) {
var ele = $(e.target);
getListByElement(ele);
return func;
}
}
fieldName.functionalityHook = [Apple.functionalityHook()];
I wonder why, as soon as the page loads, the function btw_bijtellen () is called. I wanted to call it by clicking...
var $ = function (id) {
return document.getElementById (id);
}
function btw_bijtellen () {
window.alert("we want to calculate something after clicking th button");
}
$("bereken").onclick = btw_bijtellen ();
You've added () which causes the function to execute.
For example:
var myFunc1 = function() {
alert('Hello');
}(); // <--- () causes self execution
var myFunc2 = function() {
return 5 + 5;
};
var some_value = myFunc2(); // <--- Again () causes execution (you'd expect this one)
In your case, as mentioned in comments you're basically telling the onclick to set its value to the return value of the function.
If you drop the () it should run as expected.
If you want the function to be called on click then use
$("bereken").on('click', btw_bijtellen);
Update (As per query from WAO)
If you need to pass the argument, then you need to specify as the second argument. the $.on() gets the data in the event handler
$("bereken").on('click', {key1: value1, key2: value2, keyn: valuen}, btw_bijtellen);
where, you can get your parameters from event.data
var function = btw_bijtellen(event) {
var data = event.data;
console.log(data);
var key1 = event.data.key1;
console.log(key1); // this will output value1
}
Have a read on this link jQuery $.on() api
Putting () after a function name is how you call it.
If you want to assign the btw_bijtellen to onclick then remove the () from the last line of the code in the question.
With the () there, you are calling the function and assigning its return value to onclick. Since that function has no return statement, that value will be undefined which is not what you want.
So I dont understand why the console logs 1 right away onload or something when i have one.onclick = alterIt(1) shouldn't it wait till i click one. Anyway, obviously I am not ver good at javascript, thanks for your help.
window.onload = initialize;
function initialize() {
if (1 == 1){
calculation();
}
}
function calculation() {
var one = document.getElementById('one');
one.onclick = alterIt(1);
}
function alterIt(x) {
console.log(x);
}
When you wrote:
one.onclick = alterIt(1);
...then you invoked the alterIt function and set the return value as the onclick handler. Instead, you wanted:
one.onclick = function(){ alterIt(1) };
// ...or better yet
one.addEventListener('click',function(){ alterIt(1) },false);
When the line one.onclick = alterIt(1); is executed, alterIt(1) is actually evaluated. What you want is to bind a function to one.onclick, which is only executed when the onclick event fires. You need something like
one.onclick = function() { alterIt(1) };
which doesn't bind the result of alterIt(1) to one.onclick, but rather the result of the function evaluation.
Wrap the function call like this so it doesn't fire until click:
window.onload = initialize;
function initialize() {
if (1 == 1){
calculation();
}
}
function calculation() {
var one = document.getElementById('one');
one.onclick = function(){ alterIt(1);};
}
function alterIt(x) {
console.log(x);
}
Example fiddle: http://jsfiddle.net/RkH6Q/
There are two ways that you could code to work around this issue:
//Anonymous Closures
one.onclick = function(){ alterIt(1); };
//Bind Closures
one.onclick = alertIt.bind(window, 1);
Note: Function.bind() is supported by all the browsers for a year. If you care about old browsers, anonymous closures is the way to go.
What is happening is that you are calling the alterIt function when you should just be passing it in. So remove the parenthesis like so:
one.onclick = alterIt;
I am looking for a good technique to get away from what I am tempted to do: to set a global variable.
The first time someone runs a function by clicking a button it triggers an initial function to turn a few things into draggables. Later, if they click the button a second time I want to determine if the init function has been initialized, and if so to not call it again. I could easily do this by setting a global variable from the init function and then checking that variable from the click function, but I'm wondering how to do this without setting a global variable. I would really like an example of a way to do this.
You could add a property to the function:
function init() {
init.called = true;
}
init();
if(init.called) {
//stuff
}
While #Levi's answer ought to work just fine, I would like to present another option. You would over write the init function to do nothing once it has been called.
var init = function () {
// do the initializing
init = function() {
return false;
}
};
The function when called the first time will do the init. It will then immediately overwrite itself to return false the next time its called. The second time the function is called, the function body will only contain return false.
For more reading: http://www.ericfeminella.com/blog/2011/11/19/function-overwriting-in-javascript/
Why don't you just check to see if your draggables have a class of draggable on them?
if ($('.mydiv').is('.draggable')) {
//do something
}
Function.prototype.fired = false;
function myfunc() {
myfunc.fired = true;
// your stuff
};
console.log(myfunc.fired) // false
myfunc();
console.log(myfunc.fired) // true
What you could do is unhook the init function from the prototype.
var Obj = function () {
this.init = function () {
document.write("init called<br/>");
this.init = null;
}
}
var o = new Obj();
if (o.init) document.write("exists!<br/>");
o.init();
if (o.init) document.write("exists!<br/>");
o.init();
The first if will be true and print exists! but since the function removes itself, the second if will fail. In my example, I call the second init unconditionally just to show that nothing will happen, but of course you could call it only if it exists:
if (o.init) o.init();
http://jsfiddle.net/coreyog/Wd3Q2/
The correct approach is to use the Javascript Proxy APIs to trap the function calls using apply handler.
const initFun = (args) => {
console.log('args', args);
}
const init = new Proxy(initFun, {
apply(target, thisArg, args){
target.calls = target.calls ? target.calls + 1 : 1;
return target.apply(thisArg, args);
}
});
init('hi');
console.log(init.calls); // 1
init('hello');
console.log(init.calls); // 2
I have the following code:
function sdefaults()
{
alert("test");
}
var btnpos, sbtn;
btnpos = document.getElementsByName('somePosition')[0];
sbtn = document.createElement('input');
btnpos.parentNode.insertBefore(sbtn, btnpos.nextSibling);
sbtn.type = "button";
sbtn.name = "social";
sbtn.value = "Defaults";
sbtn.onClick = sdefaults();
The button appears where I want it to and the name/value are set correctly. However when I load the page, the sdefaults() function is run and then if I click the button, nothing happens. Could anyone provide any insight into how to prevent the function from running on load and force it to only run onclick?
Thanks
Change:
sbtn.onClick = sdefaults();
to:
sbtn.onClick = sdefaults;
sbtn.onClick = sdefaults(); means: "Run the sdefaults function and store the result in sbtn.onClick.
btn.onClick = sdefaults; means: "Set sbtn.onClick to the function sdefaults", which is what you're looking for.
You have to understand the difference between function referencing, and function invocation.
Consider the following function
function foo()
{
alert( 'Hello World' );
}
Now, lets look at some samples of referencing this function. To reference a function, we use its symbol name, just like any other variable.
// Alert contents of foo
alert( foo );
// Set foo as the click handler for the body
document.body.onclick = foo;
// Assign a new function to foo
foo = function(){ alert( 'Goodbye!' ); }
Now we'll consider function invocation. This means the function executes and its return value is sent back to the calling scope.
// Invoke foo simply
foo();
// Invoke foo with a specific scope
foo.apply( this ); // or foo.call( this );
Now, it's entirely possible to modify your code snippet just by changing the code of sdefaults(). Here's how that would look.
function sdefaults()
{
return function()
{
alert("test");
}
}
Now, when you execute sbtn.onClick = sdefaults(); what happens is the onClick property receives what its expecting, a function, since we've modified sdefaults to not actually alert "test", but to return an anonymous function which itself will alert "test". (As a side note, this specific technique is commonly called a lambda or delegate function)
Hope that clears it up.