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!
If you just need to trigger a click event, you can omit the line that begins with for( . @Parag: Read it again. The loop is to click the same link 50 times, which is what it does.
To stop the click event from propagating to the <div> element, you have to call the stopPropagation() method in the event handler of the button: btn. addEventListener('click', (e) => { e.
What is the onClick handler in React? The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app. Event names are written in camelCase, so the onclick event is written as onClick in a React app.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With