bboybeatle
bboybeatle

Reputation: 567

"Uncaught TypeError: undefined is not a function " jQuery each function issue

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

Upvotes: 0

Views: 1226

Answers (2)

joona
joona

Reputation: 76

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);
});

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382454

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

Upvotes: 6

Related Questions