Should I use onclick or click method inside jQuerys document ready?

Viewed 50

I don't know if I should use onclick in HTML/PHP or a single click function bound to a specific id.

onclick example:

<button onclick="performAction()">Click me!</button>

function performAction() {
    ....
}

click example in jQuerys document ready function:

<button id="abc">Click me!</button>

jQuery(document).ready(function ($) {
    $("#abc").click(function () {
        ...
    });
});

What are the pro/cons and which one is better/faster to use? Thanks for your opinion!

2 Answers

Do not use inline event handlers, such as onclick attributes. They are no longer good practice as they tie the HTML and JS code too tightly together which is a violation of the Separation of Concerns principle.

Best practice is to use unobtrusive event handlers in either plain JS or your framework of choice.

Given the tags on your question, here's an example of that using plain JS:

document.querySelector('#abc').addEventListener('click', function() {
  // logic here...
});

Here is the same thing in jQuery:

$("#abc").on('click', function() {
  // logic here...
});

If you want to bind any event to selector then you should prefer.

jQuery(document).ready(function () {
  $("#abc").on('click', function () {
    ...
  });
});

Because on is a live event. It will call in both cases either the content already exists in the DOM or you added it after dynamically. Although, .click will not work all the time.

The second thing you can prefer this - onclick="performAction()" when you want to send some parameters to the function like this -

`<button onclick="performAction('param1', 'param2')">Click me!</button>`
Related