Skip to content Skip to sidebar Skip to footer

Using .click() In Jquery Vs Calling A Function Using Onclick

I'm rather new to jQuery but i want to know what the best practice is when making a button do something. Should i use .click() HTML

Which attaches functionality to a form button submit.

But, down the road, you realize that pressing enter/return on a text input will also submit an HTML form. To handle this, all you need to do is change one line of JavaScript:

$('#myform').on("submit", function(){
    //DO SOMETHING
});

Solution 3:

Here are my two preferred options.

Using click() in jQuery should do the same thing as onClick (even though they technically work differently) so I see no reason to pick onClick over click(). The other thing is if you ever build a Chrome extension onClick is not allowed.

Example:

$(element).click(function(){
   ...
});

Your other option is use the on() function. Unlike click() which watches a specific element on() will watch everything (in the context you define) for a event. This is useful if you have dynamic elements with the same class.

$(element).on('click', function(){
   ...
});

Both functions are useful and which depends on the situation. To answer your original question: no I see no reason to use onclick over click().

Hope that is no too off topic but that info I whish I knew when I started.

Solution 4:

Those two methods basically do the same thing. However, there is one distinct difference. The onclick attribute can only be used to bind one event, the jQuery click event can be bound multiple times on the same element.

Other than that, it's usually easier to maintain code where the markup is separated from the JavaScript code. By using the onclick attribute you have some JavaScript code mixed in with the markup.

Also, using jQuery to bind events means that you can bind an event on multiple elements at once, instead of having an attribute on each element.

Solution 5:

The .click(function(){...}); requires the browser to load jquery before performing that function but the latter i.e. function Submit(){...} is pretty more direct and requires less initial website loading time compared to the jquery method. But it's all pretty much the same in the eyes of the front end user.

Post a Comment for "Using .click() In Jquery Vs Calling A Function Using Onclick"