Search code examples
javascriptresponsiveness

Width of list item isn't adjusting past maximum pixel declaration


I have a small script that detects window width and adjusts sub navigation list items if the screen is between 600px and 1200px. The script works within constraints, however when the browser resizes past 1200px or below 600px, the width declaration stays applied to each relevant list item. However, once the page is refreshed the width is what it's supposed to be. First time poster here so please let me know what I'm missing.

Thanks

$(window).resize(function() {
var sub_menu_list_item = $('.current-menu-item .sub-menu li');
var sub_menu_list_item_count = sub_menu_list_item.length;
var divisor = ( 1 / sub_menu_list_item_count );
var width = divisor * 100;
var ww = $(window).width();

if ( ww > 600 && ww < 1200 ){
    if ( sub_menu_list_item_count % sub_menu_list_item_count === 0 ){
        sub_menu_list_item.css('width',  width + '%' );
    } 
}

});


Solution

  • It appears that you're not applying a width style to the sub-items in the "else" case. That is, when the window width is less than 600px or greater than 1200px. So those items that are sized while the window is within your 600px - 1200px width constraints will remain that way until the page is refreshed.

    If you come up with a default case, you can set the width style just like you did in your if body.

    $(window).resize(function() {
        var sub_menu_list_item = $('.current-menu-item .sub-menu li');
        var sub_menu_list_item_count = sub_menu_list_item.length;
        var divisor = ( 1 / sub_menu_list_item_count );
        var width = divisor * 100;
        var ww = $(window).width();
    
        if ( ww > 600 && ww < 1200 ){
            if ( sub_menu_list_item_count % sub_menu_list_item_count === 0 ){
                sub_menu_list_item.css('width',  width + '%' );
            } 
        } else {
            sub_menu_list_item.css('width',  'auto' );
        }
    });