Search code examples
jqueryhref

jQuery current menu code optimization


I have below code written in jQuery:

var href = window.location.href;
if (href.search('/welcome\\/') > 0)
{
    $('.menuwelcome').css('display', 'block');
    $('#welcome2').append('<b>Приглашаем субагентов</b>').find('a').remove();
    $('#welcome2').find('img').attr('src', '/static/images/arrow_black.gif');
}
if (href.search('/contacts\\/') > 0)
{
    $('.menuwelcome').css('display', 'block');
    $('#mcontacts').append('<b>Контакты</b>').find('a').remove();
    $('#mcontacts').find('img').attr('src', '/static/images/arrow_black_down.gif');
}
if (href.search('/sindbad_history\\/') > 0)
{
    $('.menuwelcome').css('display', 'block');
    $('.menuwelcome:first').append('<b>История</b>').find('a').remove();
    $('.menuwelcome:first').find('img').attr('src', '/static/images/arrow_black.gif');
}
if (href.search('/insurance\\/') > 0)
{
    $('.menusafe').css('display', 'block');
    $('#msafe').append('<b>Страхование</b>').find('a').remove();
    $('#msafe').find('img').attr('src', '/static/images/arrow_black_down.gif');
}
if (href.search('/insurance_advices\\/') > 0)
{
    $('.menusafe').css('display', 'block');
    $('.menusafe:first').append('<b>Полезная информация</b>').find('a').remove();
    $('.menusafe:first').find('img').attr('src', '/static/images/arrow_black.gif');
} 

The code above have repetitive task, Can we make the code compact? I want to minimize this code. How should I achieve this?


Solution

  • Place all the variable bits in a dictionary of arrays:

    cases = {
        '/welcome\\/' : ['.menuwelcome', '#welcome2' , 'Приглашаем субагентов', 'arrow_black.gif'     ],
        '/contacts\\/': ['.menuwelcome', '#mcontacts', 'Контакты'             , 'arrow_black_down.gif'],
        ...
    };
    

    Then loop over the cases:

    for (c in cases) {
        if (href.search(c)) {
            a = cases[c];
            $(a[0]).css('display', 'block'); 
            $(a[1]).append('<b>' + a[2] + '</b>').find('a').remove(); 
            $(a[1]).find('img').attr('src', '/static/images/' + a[3]); 
        } 
    }