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?

Ali Bassam
  • 9,691
  • 23
  • 67
  • 117
  • 2
    You should forget about example #1, use the second, get used to writing clean unobtrusive javascript. – dfsq Mar 16 '13 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. – Fabrício Matté Mar 16 '13 at 18:32
  • 1
    second one! check this link http://stackoverflow.com/questions/5871640/why-is-using-onclick-in-html-a-bad-practice – rab Mar 16 '13 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? – Ali Bassam Mar 16 '13 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. – Corey Sunwold Mar 17 '13 at 00:25

3 Answers3

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

bipen
  • 36,319
  • 9
  • 49
  • 62
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?

Community
  • 1
  • 1
Corey Sunwold
  • 10,194
  • 6
  • 51
  • 55
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.

user2148736
  • 1,283
  • 4
  • 24
  • 39