Bram Vanroy
Bram Vanroy

Reputation: 28505

Setting width of multiple elements with same class depending on their number

I'm experiencing a problem similar with one I had before. I'm trying to give multiple elements a width depending on how many of them exist.

Say I have 5 elements, their widths have to be 20%, if I have 4 25% etc. (width = 100 / n)

I thought this would work, but it doesn't:

    if ($(window).width() <= 960) {

        $("aside.widget").css("width", function(){
            var widgetLength = $("section#secondary").children("aside.widget").length();
            return 100 / widgetLength + "%"
        });
    }

Nor does:

    if ($(window).width() <= 960) {         
        $("aside.widget").css("width", 100 / widgetLength + "%");
    }

Console returns: Uncaught TypeError: Property 'length' of object [object Object] is not a function

Any thoughts? Thanks.

Upvotes: 0

Views: 1082

Answers (1)

adeneo
adeneo

Reputation: 318302

They should both work just fine, but length is not a function, so you need to change this:

var widgetLength = $("section#secondary").children("aside.widget").length();

to this:

var widgetLength = $("section#secondary").children("aside.widget").length;

then both the methods in your question will work!

Upvotes: 2

Related Questions