How can I improve my javascript jquery


#1

I am an intermediate user of javascript/jquery and I have written a block of code that will show and hide various divs with the same class name by scrolling through them with back and next buttons once the user reaches the end of the last question they can press continue.

$(document).ready(function(){

//elements and variables
var nextBtn = $("#next");
var backBtn = $("#back");
var continueBtn = $(".idvContinue");
var idvQuestionsArray = [];
var idvQuestionsArrayIndex = 0;
var idvQuestions = $('#idv-form > .highlight-box.module');
var noOfQuestions = $('#idv-form > .highlight-box.module').length;

//hiding all elements
hideAllIdvElements();

//check to see if more than one question or not
showHideElements();

//pushing all questions to the array
$(idvQuestions).each(function(){
    idvQuestionsArray.push($(this));
})

// event handlers for next & back buttons
$("#next").on("click", next);
$("#back").on("click", back);


function hideAllIdvElements(){
    $("#idv-form > .highlight-box.module:not(:first-child)").hide();
    $(continueBtn).hide();
    $(backBtn).hide();
    $(nextBtn).hide();
}

function showHideElements(){
    var index =  noOfQuestions - 1;

    //if one question than show continue button
    if (noOfQuestions <= 1){
        $(continueBtn).show();
        $(backBtn).hide();
        $(nextBtn).hide();
    }

    //show back button not on first question
    if (idvQuestionsArrayIndex > 0){
        $(backBtn).show();
    } else {
        $(backBtn).hide();
    }

    //hide next button on last question
    if (idvQuestionsArrayIndex >= index){
        nextBtn.hide();
        $(continueBtn).insertBefore("#next");
        $(continueBtn).show();
    } else {
        $(nextBtn).show();
        $(continueBtn).hide();
    }
}

function next(e){
    idvQuestionsArrayIndex = (idvQuestionsArrayIndex+1) % (idvQuestionsArray.length);
    $(".highlight-box").hide();
    if (idvQuestionsArrayIndex){
        $('.highlight-box:nth-child(' + (idvQuestionsArrayIndex + 1) +')').show();
        showHideElements();
        console.log(idvQuestionsArrayIndex);
    }
    e.preventDefault();
}

function back(e){
    $('.highlight-box').hide();
    idvQuestionsArrayIndex = (idvQuestionsArrayIndex + idvQuestionsArray.length - 1) % (idvQuestionsArray.length);
    $('.highlight-box:nth-child(' + (idvQuestionsArrayIndex + 1)    +')').show();
    showHideElements();
    console.log(idvQuestionsArrayIndex);
    e.preventDefault();
}
});

#2

@javascriptluva,
Could you provide the corresponding HTML-code ??