How to improve this jQuery code?


I'm learning jQuery and I do not always know exactly how to develop the code more cleanly, semantically, I'll end up learning. How could I improve this code?

$("#click_apoio").on('click', function( evento ){


    if( $("#institucional").hasClass('desativado') ){



asked by anonymous 05.08.2015 / 15:29

4 answers


As a good practice in javascript, it is interesting to create variables of each element that will be manipulated, to avoid many access to the DOM tree. Here are the changes I made in the code:

$(function() {

  $("#click_apoio").on('click', function(e) {

    var $institucional = $("#institucional"),
      $parceiros = $("#parceiros");

    if($institucional.hasClass('desativado')) {





About the modifications:

  • I added an anonymous jQuery function ( $(function){...}); ) to prevent the script from being loaded before the jQuery object exists on the page;
  • I created variables for each element to be manipulated, avoiding unnecessary access to the DOM tree;
  • Nested functions in each element, to organize the code and to be more readable (Ex: $institucional.removeClass('desativado').addClass('ativado'); );
05.08.2015 / 15:39

You best use your code using another logic, for example, if there are only two states ativado and desativado , then you can omit the "disabled" by leaving the default element with this behavior, and change only if there is to class="ativado" .


$("#click_apoio").on('click', function(e){
    $("#institucional, #parceiros").toogleClass('ativado');
05.08.2015 / 16:34

I do not think you have a problem with your code, it's not less professional because it does not look complex or because it has multiple lines.

Often cute algorithms are more error-prone and more difficult to debug, as well as being harder to implement and understand if another programmer needs it.

Always focus on developing simple and clear algorithms, even if this makes it verbose (there are other factors to consider).

Summarizing and using the Unix philosophy :


Rule of Clarity: Clarity is better than cleverness.

05.08.2015 / 15:45
$("#click_apoio").on('click', function( evento ){

Well, you can narrow it down a little.

05.08.2015 / 15:32