I'm trying to execute an external function on click of a DOM element without wrapping it in another function.
Say I have a function called sayHello()
, as follows:
function sayHello(){
alert("hello");
};
To execute it on click, I currently have to do this:
$("#myelement").click(function(){
sayHello();
});
Notice I am forced to wrap the single function call in yet another function. What I am trying to do is something like this
$("#myelement").click(sayHello());
Except that simply doesn't work. Can I avoid wrapping the single function call in another function in any way? Thanks!
.
Additional information: How would I achieve the same thing when I need to pass parameters to the function?
..
Additional information: Like Chris Brandsma and Jani Hartikainen pointed out, one should be able to use the bind function to pass parameters to the function without wrapping it in another anonymous function as such:
$("#myelement").bind("click", "john", sayHello);
with sayHello()
now accepting a new parameter, as such:
function sayHello(name){
alert("Hello, "+name);
}
This, unfortunately, does not seem to work... Any ideas? The Events/bind documentation is located here Thanks!
Approach 1: In this approach, we will be using the jQuery one() method. This method attaches an event to the element with the specified selector. It is named one because the event handler corresponding to the event is only executed once.
To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked. Here is the HTML for the examples in this article.
The bind()
method is now deprecated.
As of jQuery 3.0,
.bind()
has been deprecated. It was superseded by the.on()
method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.
You are better off doing all event binding with the on()
method for consistency. You can pass parameters to your handler as the second argument after the event name.
function sayHello(name){
console.log('Hello ' + name);
};
$('#myelement').on('click', 'John', sayHello);
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