Regarding jQuery functions, is it risky to use them in inline elements?

2

You have a good question here in Stackoverlow that talks about the issue of practices

Why is it bad practice to use Javascript inline?

But now, not wanting to look at bad or good practice itself, I'd like to know if it's troublesome to use inline jQuery events. That is, directly in the elements, through the methods of assigning events that the html itself provided.

Example. Instead of doing this:

$(function (){

    $('#elemento').click(function (){ 
       $('#outro-elemento').fadeIn();
    });
});

Do this:

<div id="elemento" onclick="$('#outro-elemento').fadeIn()"></div>

In fact, I've seen some programmer friends do this, and until then it had worked correctly.

But questions I'd like to know would be:

  • When doing this, I run some risk of the function not working, because, to function the assignment of events in jQuery, have to use the code inside $(function (){}) or $(document).ready() ?

  • Do I risk doing this directly on dynamically created elements? For generally, for events to work on such elements, we should use $(document).on('evento', 'elemento_dinamico') .

For example. To assign an event to a dynamic element, I should use on .

$('#container').append('<a class="teste">teste</a>');

$('#container').on('click', '.teste', function () {
      $(this).fadeOut();
});

But I could also (without risk of error), add it inline as well?

$('#container').append('<a class="teste" onclick="$(this).fadeOut()">teste</a>');
    
asked by anonymous 10.03.2016 / 19:13

1 answer

0

Think like this if you had a main.js file containing all the functions  of your application, it would be easier to do maintenance, now imagine  the same code on several pages and you have to do maintenance.

Now imagine you doing maintenance on a third-party system, the first  Would your complaint be the layout or the code?

Good Practice is not a rule, but it helps a lot and who does it ends up fitting  and creating a good accepted standard in the market where some companies have this  worry, remembering is not the rule.

    
11.03.2016 / 16:32