Skip to content

Instantly share code, notes, and snippets.

@webdawe
Created July 15, 2016 06:09
Show Gist options
  • Save webdawe/0189e4203e07c053e94009f0a23d5d8d to your computer and use it in GitHub Desktop.
Save webdawe/0189e4203e07c053e94009f0a23d5d8d to your computer and use it in GitHub Desktop.
Spread Navigation
jQuery(document).ready(
function($)
{
//calculate the container width
var containerWidth = $('ul#nav').outerWidth() - $('li.homelink').outerWidth() - $('li.last-child').outerWidth();
var liWidthTotal = 0;
var liCount = 0;
//retrieve total li width
$('ul#nav li.level0').each(
function()
{
if(!$(this).hasClass('homelink')&& !$(this).hasClass('last-child')) {
liWidthTotal += $(this).outerWidth();
liCount++;
}
}
);
//padding / margin already used in each lis using css
var paddingBuffer = 8;
//recalculate container width again with the buffer
containerWidth = containerWidth - ( paddingBuffer *(liCount +2));
//find avergage width needs to be spreaded
var widthAvg = containerWidth/liCount;
var k = 0;
var j = 0;
//check and calculate if there is any lis already having width more than the avg width and set outer width as attr
$('li.level0').each(
function()
{
if(!$(this).hasClass('homelink')&& !$(this).hasClass('last-child'))
{
if ($(this).outerWidth() > widthAvg)
{
k += $(this).outerWidth() - widthAvg;
j++;
}
else
{
$(this).addClass('need-padding');
}
$(this).attr('data-outerwidth', $(this).outerWidth());
}
}
);
//calculate the width needs to be substracted from each padding calculation
var subtractWidth = (k/(liCount- j));
$('li.need-padding').each(
function()
{
if ($(this).attr('data-outerwidth') > 0)
{
var padding = (widthAvg - $(this).attr('data-outerwidth') - subtractWidth)/2;
var paddingTop = $(this).find('a.level-top').css('padding-top');
console.log(paddingTop);
$(this).find('a.level-top').css('padding', paddingTop + padding + 'px');
}
}
);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment