Muteking
Muteking

Reputation: 1513

Jquery resize li to fit ul

I have this code so far. But it's not doing what I expect. I want the whole ul block to be filled with li's width. If you have 3 li's that would be 100/3. If you have 4 li's that would be 100/4 and so forth.

<!DOCTYPE html>
<html>
<head>

<title>Hello</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

<script language = "javascript" type="text/javascript">
  $(function(){
    var width = $("#menu").width();
        var res = Math(width / $("#menu li"));
    $("#menu li").width()= res;
  });
</script>

</head>

<ul id = "menu">
    <li><img src="img/mooo.jpg" /></li>
    <li><a href ="#">Home</a>
        <ul class = "sub1">
            <li><a href ="#">News</a></li>
        </ul>
    </li>
    <li><a href ="#">soccer</a>
        <ul class = "sub1">
            <li><a href ="#">goal</a></li>
            <li><a href ="#">ball</a></li>
            </ul>
    </li>
    <li><a href ="#">Contacts</a></li>
</ul>

<div id "main">
<h2> Goal </h2>
</div>

Upvotes: 0

Views: 1011

Answers (4)

Paulie_D
Paulie_D

Reputation: 114990

(function( $ ){
  $.fn.autowidth = function() {
    return this.each(function() {        
        $('li', this).css({'width' : (100 / $('li', this).length) + '%'})
    });
  };
})( jQuery );

$(document).ready(function(){
    $('nav > ul').autowidth();    
});

Codepen Example

Only requires box-sizing:border-box

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

You should use .length to get the count of the selected elements.

But you should only check the direct children..

So

$(function(){
    var menu = $('#menu'),
          children = menu.children();

    children.width( menu.width() / children.length );
});

Ofcourse you will have to set margins/paddings to 0 for this to work..

Upvotes: 1

user2816715
user2816715

Reputation: 46

var li_n = $('#main').children().length;
var total_width = $('#main').width();
$('#main li').each(function() { 
    $(this).width(total_width/li_n + '%');
});

I'm guessing this is what you are looking for.

Upvotes: 0

Tanel Eero
Tanel Eero

Reputation: 652

Is this what you are looking for? See the fiddle - http://jsfiddle.net/taneleero/TnXUm/

var count = 0;

$('li').each(function(){
    count++;
});

$('li').css('width', $('ul').width()/count);

Upvotes: 0

Related Questions