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>');