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

Asked

Viewed 84 times

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

    I’ve never seen that, what an ugly thing.

  • 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.

1 answer

0

Think like this if you had a main.js file containing all functions of its 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 servicing a third-party system, the first your complaint would be the layout or code?

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.