Skip to main content
2 of 5
added 15 characters in body
kosmos
  • 156
  • 2
  • 5

If you see a little your code, you will see that there are excessive repeated selectors, which (in most cases) means something goes wrong. Thinking how to improve it, finally I rewrote the entire code. The result (I hope it works):

$(function(){
    var targets = ['background', 'colour', 'description', 'logo', 'products', 'links', 'contact']; // containers
    var $elements = $('#background, #colourscheme, #description, #logo, #products, #links, #contact'); // jQuery elements
    var i, x;
    for( i = 0, x = 1; i < targets.length; i++ ){
        $('#' + x + '_open').on('click', function(){
            $('#' + targets[i] + '_container').slideToggle((500, 'easeInOutExpo'), function(){
                if( !$(this).is(':visible') ){
                    $('#' + x + '_arrow').attr('src', './resources/images/icons/right.png');
                    switch( x ){
                        case 1: $elements.show(); break;
                        case 2: $elements.not('#colourscheme').show(); break;
                        case 3: $elements.not('#description').show(); break;
                        case 4: $elements.not('#logo').show(); break;
                        case 5: $elements.not('#products').show(); break;
                        case 6: $elements.not('#contact').show(); break;
                        case 7: $elements.not('#links').show(); break;
                    }
                }
                else{
                    $('#' + x + '_arrow').attr('src', './resources/images/icons/left.png');
                    switch( x ){
                        case 1: $elements.not('#background').hide(); break;
                        case 2: $elements.not('#colourscheme').hide(); break;
                        case 3: $elements.not('#description').hide(); break;
                        case 4: $elements.not('#logo').hide(); break;
                        case 5: $elements.not('#products').hide(); break;
                        case 6: $elements.not('#contact').hide(); break;
                        case 7: $elements.not('#links').hide(); break;
                    }
                }
            });
        });
        x++;
    }
});

The first thing was to assign the names of the targets containers into an array and the elements into a jQuery object. Since we are working with an "ordered" identifiers (#1_open, #2_open...) we can assign the onclick event with a loop easily and work into it.

Since the code is almost the same, we just need to identify our current target x and proceed at convenience. There are more ways to do it, but well, this is just another one.

kosmos
  • 156
  • 2
  • 5