2
There’s a good question here at Stackoverlow that talks about the practice question
Because it is bad practice to use Javascript inline?
But now, not wanting to look at the issue of bad or good practice itself, I’d like to know if it’s problematic to use jQuery inline events. That is, directly in the elements, through the methods of assigning events that 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 doing this, and so far it had worked correctly.
But questions I’d like to know are:
In doing so, I run some risk that the function will not work, on account of, to function event assignment in jQuery, having to use the code within
$(function (){})
or else$(document).ready()
?Do I take risks doing this directly on dynamically created elements? For generally, for events to work on such elements, we must use
$(document).on('evento', 'elemento_dinamico')
.
For example. To assign an event to a dynamic element, I must use on
.
$('#container').append('<a class="teste">teste</a>');
$('#container').on('click', '.teste', function () {
$(this).fadeOut();
});
But I could also (no risk of error), add it inline, like this?
$('#container').append('<a class="teste" onclick="$(this).fadeOut()">teste</a>');
I’ve never seen that, what an ugly thing.
– Renan Gomes
Don’t say that, kkkk. I’ve seen colleagues do it ;). The boss asked to speed up the process, no one cares about good practices.
– Wallace Maxters