Reputation: 2211
greetings,
I'm new with java script so bear with me!
I want to achieve something using JQuery
selectors.
I have a list menu. It looks like this...
<ul style="width:auto">
<li>item one</li>
<li>item two</li>
<li>item three</li>
<li>item four</li>
<li>item five</li>
</ul>
Okay, so currently I'm using the parseInt
function to retrieve the integer value of the current width of the ul
.
var ul = $("ul");
var currentWidth = parseInt(ul.width);
var maxWidth = 400;
With that giving me the current width I'd like to now create an if statement. This is where it gets really tricky for me.
if(currentWidth <= maxWidth){
alert('great job, do nothing');
}
else {
// WHAT DO I DO?!
// I need to take all the elements that makes the ul exceed that maxWidth variable and assign them to a new array called extraItems
}
So how do I get those items. I fear this is so far beyond the basic!
Any help would be so greatly appreciated!
Objective example image: imageShack link
Upvotes: 0
Views: 428
Reputation: 38672
Here is how I would deal with it:
// given these values:
var ul = $("ul");
var maxWidth = 200;
// the total width counter
var acc = 0;
// find the li's and use the map (or filter) function to filter away unwanted elements
var overflow = ul.find('li').map(function(){
// add current elm's width to our total
acc += $(this).outerWidth();
// within bounds - return nothing
if ( acc < maxWidth ) {
return null;
}
// limit reached - return element
else {
return this;
}
});
// we are left with only the "overflow" elements...
overflow.hide();
Upvotes: 1
Reputation: 86443
Check out this community wiki post by Andreas Grech... you can make your own selector to do this as well.
Edit: Oh and after reading what your ultimate goal is (hiding the overflow) why not just use the CSS class overflow:hidden
on your content wrapper, then use a plugin like scrollTo to move it around?
Edit #2 LOL sorry for editing so much... if you are just doing this to learn, try this code (I also have it running in a pastebin), also make sure you look at the CSS, the li
by default will have 100% width:
$(document).ready(function(){
var ul = $("ul");
var currentWidth = ul.width();
var maxWidth = 400;
if(currentWidth <= maxWidth){
alert('great job, do nothing');
} else {
var liWidth = 0;
var done = false;
ul.find('li').each(function(indx){
liWidth += $(this).width();
if (liWidth > maxWidth && !done){
ul.find('li:gt(' + (indx-1) + ')').hide();
var done = true;
}
})
}
var savedLi = ul.find('li:hidden');
alert( savedLi.length + ' elements were hidden');
})
Upvotes: 1
Reputation: 39966
else {
var extraItems = [];
$('ul li').each(function(i, e) {
if ($(e).width() > maxWidth) {
$(e).remove(); //? dunno if you want to remove em, but here's how
extraItems.push(e);
}
});
...
}
Upvotes: 4