0

This is a pretty basic question. I have this block of code which I thought was OK but its throwing up an error...

Uncaught TypeError: undefined is not a function 

Here is the code in question

$('.colourbox').each(function(i){
// select visible children
var visibleDivs = $(this).children('div').length;

// use whatever width calculation you'd like...
var targetWidth = 300 / visibleDivs.length - 1;

// apply the width to the divs
visibleDivs.width(targetWidth);
});

Thanks

2 Answers 2

6

visibleDivs is a number :

var visibleDivs = $(this).children('div').length;

So it doesn't have a width function which make this line fail :

visibleDivs.width(targetWidth);

You probably want

$('.colourbox').each(function(i){
   // select visible children
   var visibleDivs = $(this).children('div');

   // use whatever width calculation you'd like...
   var targetWidth = 300 / visibleDivs.length - 1;

   // apply the width to the divs
   visibleDivs.width(targetWidth);
});

But you should have solved this issue yourself using the developer tools of your browser :

  1. look at the exact line of the error given in the console
  2. if that's not enough, debug and, line after line, look at the value of your variables
Sign up to request clarification or add additional context in comments.

Comments

0

Variable visibleDivs has a value of a number of child divs.

var visibleDivs = $(this).children('div').length;

What you probably wan't to have there is a list of child divs instead:

var visibleDivs = $(this).children('div');

Full example:

$('.colourbox').each(function(i){
    // select visible children
    var visibleDivs = $(this).children('div');

    // use whatever width calculation you'd like...
    var targetWidth = 300 / visibleDivs.length - 1;

    // apply the width to the divs
    visibleDivs.width(targetWidth);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.