minified javascript codes, I don't understand, can anyone explain it

76 Views Asked by At

I'm trying to improve myself by working on codes. I can understand its normal state without any problems. In the sample code below, jquery, value reading, value assignment and if-else queries are nested. I could not get the code in a meaningful readable way. Can anyone write the code below in a simple expanded readable format?

$('.input-required input, .input-required select, .input-required textarea').on('focusin keyup', function () {
  var inputSpan = $(this).parent().find('span').text();
  $(this).val() != inputSpan && '' != $(this).val() && $(this).parent().find('span').addClass('input-style-1-active').removeClass('input-style-1-inactive'),
  '' === $(this).val() && $(this).parent().find('span').removeClass('input-style-1-inactive input-style-1-active')
});

$('.input-required input, .input-required select, .input-required textarea').on('focusout', function () {
  $(this).parent().find('span').text();
  '' === $(this).val() && $(this).parent().find('span').removeClass('input-style-1-inactive input-style-1-active'),
  $(this).parent().find('span').addClass('input-style-1-inactive')
});

The extended version of the first code block is correct as below?

$('.input-required input, .input-required select, .input-required textarea').on('focusin keyup', function () {
  var inputSpan = $(this).parent().find('span').text();
  if(($(this).val() != inputSpan) && ('' != $(this).val())){
    $(this).parent().find('span').addClass('input-style-1-active').removeClass('input-style-1-inactive');
  }else{
    $(this).parent().find('span').removeClass('input-style-1-inactive input-style-1-active');
  }
});
1

There are 1 best solutions below

0
On

Whoever wrote that did not write it with maintenance in mind. Is it generated code by some tool?

I would think it could be condensed to

$(':input.input-required').on('input focusout', function (e) {
  let $inputSpan = $(this).parent().find('span'), 
      text = $inputSpan.text(), 
      val = $(this).val();

  if (val && val != text) {
    $inputSpan
      .addClass('input-style-1-active')
      .removeClass('input-style-1-inactive')
  }
  else { 
   $inputSpan
     .removeClass('input-style-1-active')
     .addClass('input-style-1-inactive')
  }
});

Which may be even more readable with toggleClass