How to improve this jQuery code?

9

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 ){

    evento.preventDefault();

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

        $("#institucional").removeClass('desativado');
        $("#institucional").addClass('ativado');
        $("#parceiros").removeClass('ativado');
        $("#parceiros").addClass('desativado');

    }

});
    
asked by anonymous 05.08.2015 / 15:29

4 answers

10

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) {

    e.preventDefault();
    var $institucional = $("#institucional"),
      $parceiros = $("#parceiros");

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

        $institucional.removeClass('desativado')
          .addClass('ativado');

        $parceiros.removeClass('ativado')
          .addClass('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
7

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

Example:

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

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
4
$("#click_apoio").on('click', function( evento ){
    evento.preventDefault();
    if($("#institucional").hasClass('desativado')){
        $("#institucional").removeClass('desativado').addClass('ativado');
        $("#parceiros").removeClass('ativado').addClass('desativado');
    }
});

Well, you can narrow it down a little.

    
05.08.2015 / 15:32