Addeventlistener Calls the Function Without Me Even Asking It To

addEventListener calls the function without me even asking it to

Quoting Ian's answer:

Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined...because all the function does is alert and doesn't return anything). Either call the function in an anonymous function (like your first example) or alter the function to return a function.

function message_me(m_text){
alert(m_text)
}

second.addEventListener('click',
function() {
message_me('shazam');
}
);

Here's an updated fiddle.

When I call .addEventListener(click, myFunction(i), false); It runs my function on the call and not on the click

addEventListener needs to assign the function variable. In your code you are calling the function immediately using (). To fix it you can remove them.

classname[selected].addEventListener("click", formating, false);

To pass argument to your function you can either wrap it in an anonymous function and call it or use bind (source):

classname[selected].addEventListener('click', formating.bind(null, event, arg1, ... ));

addEventListener( click ,...) firing immediately

When you are binding event you are calling the function document.getElementById("tooltip-link1").addEventListener("click",displayTooltip(2));

You need to pass reference to the function.

Change to below

document.getElementById("tooltip-link1").addEventListener("click", function(){
displayTooltip(2)
});

How the function is used without parenthesis in addEventListener?

Because in this context, addItem is used as a function reference rather than the return value of the function.

If you did this:

addButton.addEventListener('click', addItem());

Then addItem would be executed straight away, and whenever addButton was clicked, the return value of addItem (which is undefined) would be called. This would result in an error, because undefined is not a function.

Here, you're saying when I click addButton, lookup the function reference I passed, and execute it.

You can also write this two different ways:

addButton.addEventListener('click', "addItem()");
addButton.addEventListener('click', function() {
addItem();
});

Both of the above will still result in the same output as your original code.



Related Topics



Leave a reply



Submit