How to be less repetitive in my JavaScript codes?

1

My code looks big and clumsy, is there a way to make it smaller? Something like "easier to write", or less?

Here's my example, as you can see, I need to repeat this block 5 times , to display only one button at a time and its <div> , One for each button I press.

Am I right? would it be anyway?

function analysisShowPage1(){
    $('#page01').removeClass('btn-warning').addClass('btn-success');
    $('#page02').removeClass('btn-success').addClass('btn-warning');
    $('#page03').removeClass('btn-success').addClass('btn-warning');
    $('#page04').removeClass('btn-success').addClass('btn-warning');
    $('#page05').removeClass('btn-success').addClass('btn-warning');
    document.getElementById('analysisFullGraphContainer').style.display = 'block';
    document.getElementById('analysisFullGraphContainer2').style.display = 'none';
    document.getElementById('analysisFullGraphContainer3').style.display = 'none';
    document.getElementById('analysisFullGraphContainer4').style.display = 'none';
    document.getElementById('analysisFullGraphContainer5').style.display = 'none';
    document.getElementById('copyGraph01').style.display = 'block';
    document.getElementById('copyGraph02').style.display = 'none';
    document.getElementById('copyGraph03').style.display = 'none';
    document.getElementById('copyGraph04').style.display = 'none';
    document.getElementById('copyGraph05').style.display = 'none';
}
    
asked by anonymous 09.08.2016 / 02:31

2 answers

5

Not always repetitive code is bad. It may reduce it, but it may become more difficult to understand. The key to eliminating repetitions is to find a pattern and change what it varies. There are several ways to reach the goal.

Since a minimal, computable and verifiable example has not been made, I'll make a code that probably works, but I can not test it:

for (var i = 1; i < 6; i++) { 
    $('#page0' + i).removeClass('btn-warning').addClass(i == 1 ? 'btn-success' : 'btn-warning');
    document.getElementById('analysisFullGraphContainer' + i).style.display = i == 1 ? 'block' : 'none';
    document.getElementById('copyGraph0' + i).style.display = i == 1 ? 'block' : 'none';
}
    
09.08.2016 / 02:41
1

You can iterate all inside a for

Deselect:

function analysisShowPage1() {
  for (i = 1; i <= 5; i++) {
    $('#page' + i).removeClass('btn-warning').addClass('btn-success');
    document.getElementById('analysisFullGraphContainer' + i).style.display = 'block';
    document.getElementById('copyGraph' + i).style.display = 'block';
  }
}

I recommend only removing 0 from the variable name, the numeric type, takes 01 as 1 for example.

    
09.08.2016 / 02:40