Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute an external function when an element is clicked?

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!

like image 822
Yuval Karmi Avatar asked Jul 25 '09 23:07

Yuval Karmi


People also ask

How do you attach a event to element which should be executed only once?

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.

How do you check if the element is clicked?

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.


1 Answers

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);
like image 120
Udo E. Avatar answered Oct 07 '22 01:10

Udo E.