CptFishPants
CptFishPants

Reputation: 145

Iteration of Jquery functions

I made: http://jsfiddle.net/ablueman/sfjL9kyr/ and wanted to apply this to a class. So every DIV I put that class in, it would show the width and height.

I started trying to create it but I've hit a brick wall: http://jsfiddle.net/ablueman/2uvpk2d5/

In the first DIV it puts 2 working div sets in. In the second DIV it puts 2 non-working div sets in. enter image description here

I've tried everything I can think of, but Im sure its just a fundamental error. Please help.

if ($('div').hasClass('change')) { 
    $('.change').each(function (iterate, val) {
    twoDivs = "<div id='changelog"+iterate+"'></div><div style='clear: right;'></div>";
    $('.change').append(twoDivs);      

     $("#changelog"+iterate).text(' W: ' + $('.change').width() + 'px , H:' + $('.change').height() + 'px ');
     $(window).resize(function() {
     $("#changelog"+iterate).text(' W: ' + $('.change').width() + 'px , H:' + $('.change').height() + 'px ');
     });
 });
}

Andy

Upvotes: 0

Views: 61

Answers (2)

Sameer Azazi
Sameer Azazi

Reputation: 1497

Yup there is a small mistake. What you are trying to do is foreach div you are trying to append a footer and register change event to that. But while attaching footer div and registering event you are referring both divs instead of the one you are iterating on. you just need to hold a reference in a variable.

I have updated your script.

    if ($('div').hasClass('change')) { 
    $('.change').each(function (iterate, val) {
        var self = $(this);
    twoDivs = "<div id='changelog"+iterate+"'></div><div style='clear: right;'></div>";
    self.append(twoDivs);      

     $("#changelog"+iterate).text(' W: ' + self.width() + 'px , H:' + self.height() + 'px ');

     $(window).resize(function() {
     $("#changelog"+iterate).text(' W: ' + self.width() + 'px , H:' + self.height() + 'px ');
     });

 });
}

Here is JSFiddle Link with updated script.

Upvotes: 1

Viswanath Donthi
Viswanath Donthi

Reputation: 1821

After reviewing your code there were syntactial errors while traversing element with each function. Here's your updated code.

if ($('div').hasClass('change')){ 
    $('.change').each(function(iterate){
        twoDivs = "<div id='changelog"+iterate+"'></div><div style='clear: right;'></div>";
        $('.change').append(twoDivs);      

        $("#changelog"+iterate).text(' W: ' + $('.change').width() + 'px , H:' + $('.change').height() + 'px ');
        $(window).resize(function() {
            $("#changelog"+iterate).text(' W: ' + $('.change').width() + 'px , H:' + $('.change').height() + 'px ');
        });
    });
}

Upvotes: 0

Related Questions