Skip to content

Instantly share code, notes, and snippets.

@heesienooi
Created April 16, 2012 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heesienooi/2395485 to your computer and use it in GitHub Desktop.
Save heesienooi/2395485 to your computer and use it in GitHub Desktop.
JavaScript: Dynamic Menu Calculation
/* Author: Hee Sien Ooi < heesien.ooi@butterfly.com.au >
* Calculate and set menu items width and background according to menu ul width
* Version: 1.0
* Known issue: Maybe backgroud position for each item is not accuate, please check and tell me.
* Notes: Must set menu width and image in css
* Requirement: jQuery 1.7.2 +
* Usage: 1. Make sure you have your ul width (ie. #nav ul { width:960px; })
2. jQuery('#navi li').dynamicMenuCal (); (add cufon ready if using cufon)
*/
jQuery.fn.dynamicMenuCal = function() {
var LI = this;
// Calculating offset value for each item
var outer = 0;
var rem = LI.parent().width();
LI.each(function(i) {
//rem -= jQuery(this).width();
rem -= jQuery(this).outerWidth();
outer += jQuery(this).outerWidth() - jQuery(this).width();
});
var offset = Math.round(rem/LI.size());
// Setting their width and background position
var border = 0;
var sum = [0];
LI.each(function(i) {
if (i >= LI.size()-1) return false;
var li = jQuery(this);
border += jQuery(this).outerWidth() - jQuery(this).width();
li.css('background-position', sum[i]+'px top');
li.css('width', li.width()+offset+'px');
sum.push(sum[i] - li.width() - border);
//sum.push(sum[i] - li.width());
});
//sum[sum.length-1] -= outer;
LI.last().css('background-position', sum[sum.length-1]+'px top');
LI.last().css('width', LI.parent().width()+sum[sum.length-1]+'px');
// Set hover background position for items
LI.each(function(i) {
var li = jQuery(this);
li.hover( function() {
jQuery(this).css('background-position', sum[i]+'px bottom');
}, function() {
jQuery(this).css('background-position', sum[i]+'px top');
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment