Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm working on an application that has some repeating code. Wheneven I try to reduce this code it breaks.

For example this code is repeating itself
$(this).before(leftArrowHTML); $(this).after(rightArrowHTML);

Also, if you see there is much more code there. So what should be the efficient way to handle that?

var left = '.lessonNavigation li.expanded.left';
var actLsn = '.lessonNavigation li.activeLesson';
var right = '.lessonNavigation li.expanded.right';
var leftArrowHTML = '<li class="left arrow"><i class="icon icon-arrow-left"></i></li>';
var rightArrowHTML = '<li class="right arrow"><i class="icon icon-arrow-right"></i></li>';

$('.lessonNavigation ').on('click', '.expandable li', function () {
    if ($(this).is(".arrow,.inactiveRightArrow,.inactiveLeftArrow,.activeLesson")) {
        return false;
    }

    $('.arrow, .inactiveRightArrow, .inactiveLeftArrow').remove();

    if ($(this).is(':last-child')) {
        $(this).attr('class', 'activeLesson');
        $(this).prev().attr('class', 'expanded left');
        $(this).prev().prev().attr('class', 'expanded left');
        $(this).before(leftArrowHTML);
        $(this).after(rightArrowHTML);
        $('.arrow.right').attr('class', 'inactiveRightArrow');

    } else if ($(this).is(':first-child')) {

        $(this).attr('class', 'activeLesson');
        $(this).next().attr('class', 'expanded right brw');
        $(this).next().next().attr('class', 'expanded right');
        $(this).before(leftArrowHTML);
        $(this).after(rightArrowHTML);
        $('.arrow.left').attr('class', 'inactiveRightArrow');

    } else {

        $('.lessonNavigation li').attr('class', 'dn');
        // .attr('class', 'dn')
        $(this).attr('class', 'activeLesson');
        $(this).prev().attr('class', 'expanded left');
        $(this).next().attr('class', 'expanded right');
        $(this).before(leftArrowHTML);
        $(this).after(rightArrowHTML);
    }

    console.log(this)
});
share|improve this question
1  
Could you mention what this code does? –  Jamal Jun 8 at 18:12
1  
so if you put $(this).before(leftArrowHTML); $(this).after(rightArrowHTML); outside the if's it don't work anymore? –  Marco Acierno Jun 8 at 18:21
1  
Can you create a JsFiddle with working HTML and JavaScript? It's hard to tell how this code can be shortened without seeing the HTML. –  Greg Burghardt Jun 9 at 17:14
    
honestly, I wouldn't write this code any shorter... it's already plenty short –  Vote to Close Jun 11 at 2:40
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.