1

When generating HTML from server, for example, via echo in PHP, is it better to assign events:

<div>
    <input type="button" onclick="Click(123)"/>
</div>

function Click(x)
{
    var id = x;
    //Do Ajax Call
}

Or to declare events in JQuery/JavaScript...

<div id="123">
    <input type="button" class="myButton"/>
</div>


$(".myButton").click(function(){

   //Fetch the ID as well
   var parentID = $(this).parent('div').attr('id');
   //Then do an Ajax Call

});

Which is the best practice?

5
  • 2
    You should forget about example #1, use the second, get used to writing clean unobtrusive javascript. Commented Mar 16, 2013 at 18:31
  • Better is subjective. Web 2.0 standards suggest using unobtrusive JS, that is, no onevent attributes. I'd use your second approach, but with data- attribute instead of id so that your behavior stays separately from structure, though some will consider data- as mixing behavior with structure as well. Commented Mar 16, 2013 at 18:32
  • 1
    second one! check this link stackoverflow.com/questions/5871640/… Commented Mar 16, 2013 at 18:32
  • After all the comments and answers, its clear that the second approach is better, but wouldn't fetching the ID add more time for execution rather than the ID sent as a Parameter? Commented Mar 16, 2013 at 18:43
  • 1
    @Ali Bassam - the performance hit is so incredibly small its not even worth considering. Even if you had to do it thousands of times a second I'm not sure there would be a measurable (in microseconds) impact on performance and definitely no user perceptible performance impact. Commented Mar 17, 2013 at 0:25

3 Answers 3

1

It makes no difference whether the HTML is dynamically generated or not. You should generally prefer to use unobtrusive Javascript either way.

Also see: Why is using onClick() in HTML a bad practice?

Sign up to request clarification or add additional context in comments.

Comments

1

second approach is better .. as web 2.0 standards suggest using unobtrusive JS rather than onevent attributes.... however since the element is generated dynamically... your second approach might not work... you need io delegate your click event to the closest static parent using on

$(document).on('click',".myButton",function(){

  //Fetch the ID as well
  var parentID = $(this).parent('div').attr('id');
 //Then do an Ajax Call

});

read more about on() event

Comments

0

The second method is better because a) you don't have to edit your HTML code and b) you have better possibility how to handle your events from your JS code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.