Link to home
Create AccountLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

How does this Javascript work?

I've got some JS I'm attempting to deconstruct so I can add some functionality to it. First, however, I want to understand what I'm looking at. Here's what I've got:

First the JS itself:

define(['/assets/js/views/app2/custom_checkbox_and_radio.js','jquery'],function(){
    return function(){
      $('.at_filters label').click(function(){
        $(this).siblings('.checkbox').click();
      });
      $('input[name="filt"]').on('change',function(){
        if(this.value=='all'){
          if($(this).is(':checked')) $('input[name="filt"]').attr('checked', true);
          else $('input[name="filt"]').attr('checked', false);
        } else {
          $('input[name="filt"][value="all"]').attr('checked', false);
        }
        var show = [];
        var left = true;
        $('input[name="filt"]:checked').each(function(){
          show.push($(this).val());
        });
        var year = '';
        var month = '';
        $('.at_timeline_list li').each(function(){
          if($(this).hasClass('yearheader')){
            if(year && year.data('delete')) year.slideUp();
            else if(year) year.slideDown();
            year = $(this);
            year.data('delete', true);
          } else if($(this).hasClass('monthheader')){
            if(month && month.data('delete')) month.slideUp();
            else if(month) month.slideDown();
            month = $(this);
            month.data('delete', true);
          } else if($(this).hasClass('event')){
            if(show.indexOf($(this).data('type'))!=-1){
              $(this).removeClass('left').removeClass('right');
              $(this).addClass(left?'left':'right');
              left=!left;
              if($(this).css('display')!='list-item') $(this).slideDown();
              year.data('delete',false);
              month.data('delete',false);
            } else {
              if($(this).css('display')=='list-item') $(this).slideUp();
            }
          }
        });
        if(year && year.data('delete')) year.slideUp();
        else if(year) year.slideDown();
        if(month && month.data('delete')) month.slideUp();
        else if(month) month.slideDown();
      });

      //Account Search
      $('input.at_search').keypress(function(e){
        if(e.which == 13){
          $(this).siblings('.magnificon').click();
        }
      });
      $('.at_searchwrap .magnificon').click(function(){
        if(!$('.at_search').val()) return;
        pf.ajax({
          url:'/app/accounttimeline',
          data:{searchfor:$('.at_search').val()},
          type:'post',
          dataType:'json',
          success:function(res){
            if(res.success && res.body){
              if(res.loadAccount){
                pf.apps.loadApp({
                  appurl:'/app/accounttimeline',
                  postdata:{accountkey:res.loadAccount},
                  refresh:new Date()
                });
              } else pf.dialog(res.body, 'Search Results');
            } else {
              pf.dialog('There has been an issue processing your request. I apologize for the inconvenience, please try again.', 'Error');
            }
          }
        });
      });

      setupLabel();
    };
});

Open in new window


Here's a screenshot of the page:

User generated image
I want to break this down into several questions, just so I'm not wearing out my welcome.  What I want to do is define that which I understand and ask for confirmation on those things and then crescendo to that point where I've got a question. That said, here's the first "dilemma:"

define(['/assets/js/views/app2/custom_checkbox_and_radio.js','jquery'],function(){

I'm defining a series of variables located on the "customer_checkbox_and_radio.js" page (https://github.com/amdjs/amdjs-api/wiki/AMD). The next part says, "function." I'm thinking this is shorthand for "document.ready..." In other words, don't try to fire the function that's documented immediately following this syntax until the entire page is loaded.

The next part baffles me. I'm returning a function?

return function(){

The next body of code has this:

  $('.at_filters label').click(function(){
        $(this).siblings('.checkbox').click();
      });

What's happening here? I've got a class "at_filters label" which matches my code here:

<div class="at_searchwrap clearfix"><input class="at_search" placeholder="Search by first name, last name, or accountid."/><span class="magnificon"></span></div>
    <ul class="at_filters">
      <li>
        <span class="checkbox">
          <input type="checkbox" name="filt" value="all" checked/>
        </span><label>All</label>
      </li>
      <li>
        <span class="checkbox">
          <input type="checkbox" name="filt" value="transaction" checked/>
        </span><label>Transactions</label>
      </li>
      <li>
        <span class="checkbox">
          <input type="checkbox" name="filt" value="statement" checked/>
        </span><label>Statements</label>
      </li>
      <li>
        <span class="checkbox">
          <input type="checkbox" name="filt" value="note" checked/>
        </span><label>Notes</label>
      </li>
      <li>
        <span class="checkbox">
          <input type="checkbox" name="filt" value="comment" checked/>
        </span><label>Task Comments</label>
      </li>
	  <li>
        <span class="checkbox">
          <input type="checkbox" name="filt" value="personal_payments" checked/>
        </span><label>Personal Payments</label>
      </li>
    </ul>

Open in new window


Every one of these checkboxes is tied to this function, but what is that function doing?

What do you think?
SOLUTION
Avatar of Alexandre Simões
Alexandre Simões
Flag of Switzerland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
ASKER CERTIFIED SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Avatar of Bruce Gust

ASKER

Gentlemen! Thanks so much for your time! Let me explain back to you what you have above and then feel free to weigh in on the second part of the question (https://www.experts-exchange.com/questions/28961568/How-does-this-Javascript-work-Part-II.html).

Here's the custom_checkbox_radio...js:

// Custom checkbox and radios
function setupLabel() {
    // Checkbox
    var checkBox = ".checkbox";
    var checkBoxInput = checkBox + " input[type='checkbox']";
    var checkBoxChecked = "checked";
    var checkBoxDisabled = "disabled";

    // Radio
    var radio = ".radio";
    var radioInput = radio + " input[type='radio']";
    var radioOn = "checked";
    var radioDisabled = "disabled";

    // Checkboxes
    if ($(checkBoxInput).length) {
        $(checkBox).each(function(){
            $(this).removeClass(checkBoxChecked);
        });
        $(checkBoxInput + ":checked").each(function(){
            $(this).parent(checkBox).addClass(checkBoxChecked);
        });
        $(checkBoxInput + ":disabled").each(function(){
            $(this).parent(checkBox).addClass(checkBoxDisabled);
        });
    }

    // Radios
    if ($(radioInput).length) {
        $(radio).each(function(){
            $(this).removeClass(radioOn);
        });
        $(radioInput + ":checked").each(function(){
            $(this).parent(radio).addClass(radioOn);
        });
        $(radioInput + ":disabled").each(function(){
            $(this).parent(radio).addClass(radioDisabled);
        });
    }
}

$(document).ready(function(){
    $("html").addClass("has-js");
    //console.log('docready');
    // First let's prepend icons (needed for effects)
    $(".checkbox, .radio").filter(function(){
        return $(this).data('prepended')?false:true;
    }).prepend("<span class='icon'></span><span class='icon-to-fade'></span>").data('prepended',true);

    $(document).off('click.customchecksnsech').on('click.customchecksnsech', ".checkbox, .radio", function(e){
        $(this).children('input[type="checkbox"]').attr('checked',!$(this).children('input').attr('checked')).change();
        $(this).children('input[type="radio"]').attr('checked',true).change();
        //$(this).children('input[type="radio"]').change();
        //console.log($(this));
        setupLabel();
    });
    setupLabel();
});

function refreshInputs(){
    $(".checkbox, .radio").filter(function(){
        return $(this).data('prepended')?false:true;
    }).prepend("<span class='icon'></span><span class='icon-to-fade'></span>").data('prepended',true);
    setupLabel();
}

Open in new window


I'm establishing the digital presence of those entities and then "coupling" those entities with the functionality that's documented after the "return function."

At the beginning of the "return function," you've got this:

      $('.at_filters label').click(function(){
        $(this).siblings('.checkbox').click();
      });

If I'm hearing the tone of your voice correctly, it's almost pointless. What you're doing is coupling the checkboxes with the labels that go along with the "at_filters" class. And while it may work, it's not good programming.

Correct?

Let me know and feel free to take a look at Part II (https://www.experts-exchange.com/questions/28961568/How-does-this-Javascript-work-Part-II.html
If I'm hearing the tone of your voice correctly, it's almost pointless.
No, it's stupid :)
It denotes a big lack of HTML knowledge. Just delete it and use the "for" attribute on the labels.
Sorry for my language, I'm usually not this aggressive, but there are certain things that really drive me mad, and this kind of code is one of them :)