HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Grouping similar jQuery functions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
functionssimilarjquerygrouping

Problem

I want to group the two very similar jQuery functions into just one. Any idea?

HTML:

">
                   
                           
                            
                         
                            
                             
                      


jQuery:

$(document).on('click', '#plus', function(e){
    var progress = parseInt( $('#progress').val() ) + 5;
    if ( progress = 0 ) {
        $('#progress').val( progress );
    }
    else{
        $('#progress').val( 0 );    
    };
});

Solution

First step would be to extract a function that updates the input:

function modifyProgress(delta) {
  var element = $('#progress');
  var progress = +element.val() + delta;
  element.val( isNaN(progress) ? 0 : progress  100 ? 100 : progress;
);
}


BTW, never ever use parseInt with out its second parameter (radix). Some browsers interpret numbers starting with a leading 0 (zero) as octal, so that an input of "09" throws an error and "010" to returns 8. Better is to use the unary plus operator.

This simplifies the event handler:

$(document).on('click', '#plus, #minus', function(e){
   modifyProgress(5 * (this.id === "plus" ? 1 : -1));
})


EDIT: You should consider storing your progress value somewhere other inside the input such as a data model (see MVC). Keeping data/logic separate from the GUI is always a good thing. It also avoids needing to re-parse the number every time. And you can "hide" the checking of overflow or underflow inside the model.

Code Snippets

function modifyProgress(delta) {
  var element = $('#progress');
  var progress = +element.val() + delta;
  element.val( isNaN(progress) ? 0 : progress < 0 ? 0 : progress > 100 ? 100 : progress;
);
}
$(document).on('click', '#plus, #minus', function(e){
   modifyProgress(5 * (this.id === "plus" ? 1 : -1));
})

Context

StackExchange Code Review Q#45412, answer score: 4

Revisions (0)

No revisions yet.