Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between "click" and "onclick" when creating an element with jQuery?

What's the difference between

$("<a>", {
    "id" : "myId",
    "text" : "my link",
    "href" : "#",
    "onclick" : function() { return false; }
);

and

$("<a>", {
    "id" : "myId",
    "text" : "my link",
    "href" : "#",
    "click" : function() { return false; }
);

?

like image 776
supertonsky Avatar asked Dec 13 '12 04:12

supertonsky


People also ask

What's the difference between Onclick and click?

click is a function on HTML elements you can call to trigger their click handlers: element. click(); onclick is a property that reflects the onclick attribute and allows you to attach a "DOM0" handler to the element for when clicks occur: element.

What is click in jQuery?

jQuery click() MethodThe click event occurs when an element is clicked. The click() method triggers the click event, or attaches a function to run when a click event occurs.

What is the difference between click and Onclick in angular?

The difference is that the first ( click ) is an event listener, and the second ( onclick ) is an event handler content attribute.

What is the difference between Onclick and event listener?

addEventListener can add multiple events to a particular element. onclick can add only a single event to an element. It is basically a property, so gets overwritten.


1 Answers

Using onclick creates an attribute, and its value should be a string that refers to a function, not an actual function. Using click creates a property on the element, and its value should be the function itself.

So, the first one is written incorrectly; should be like this:

$("<a>", {
    "id" : "myId",
    "text" : "my link",
    "href" : "#",
    "onclick" : "somefunction()"
} );

where "somefunction" is defined in the global scope:

window.somefunction = function() { return false; }
like image 76
McGarnagle Avatar answered Oct 15 '22 10:10

McGarnagle