Sherwin Flight
Sherwin Flight

Reputation: 2363

jQuery 'each' function and 'this' variable

I have created a Fiddle here: https://jsfiddle.net/svyyow89/4/

As you resize the screen some elements in the row are hidden, and a counter shows the number of hidden elements.

I had this working properly when I only has a single "container" element, but I need the script to do the same thing for every element with the "container" class.

As shown in my fiddle I have the code working to show/hide elements as the screen is resized. However it appears as though the text counters just set themselves to the same value, when each "container" contains a different number of "items". I thought my use of the "this" variable would mean the code would treat the elements in "container" separately.

I would appreciate any help you can provide.

$(window).on('resize',function() {

    $(".container").each(function(){
          var numImages = $(this).find(".item").length;
          var numToShow = numImages;
          var screenWidth = $( window ).width();
          var numFit = Math.floor(screenWidth / 80);

          $(this).find( ".item" ).removeClass( "item-show" );
          $(this).find( ".more" ).removeClass( "more-show" );
          $(this).find('.more').html('');

          if(numFit < numImages){
              numToShow = numFit - 1;
              $(this).find('.more').addClass("more-show");
          } else {
              $(this).find('.more').removeClass("more-show");
          }

          $(this).find( ".item" ).slice( 0, numToShow ).addClass( "item-show" );

          var numHidden = $(".container > *").filter(":hidden").size();

          $(this).find('.more').html('+'+numHidden+' more');

   });
});

$(document).ready(function() {
    $(window).trigger('resize');
});

Upvotes: 2

Views: 71

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074276

Mostly you're doing it right, you just missed out one statement:

var numHidden = $(".container > *").filter(":hidden").size();

You need to use this there, too:

var numHidden = $(this).children(":hidden").size();

(Using children because you used the direct child combinator >, and children can accept a filter so we can fold the filter into it.)


Separately, though, remember that $() is a function. Every time you call it, it has to do work, and every time you call it, it allocates memory that eventually has to be cleaned up (memory churn). So rather than writing $(this) everywhere, do it once (in the each callback) and remember the result:

var $this = $(this);

This is important in any performance-sensitive code (such as a resize handler), and generally (not always) good practice anyway.

Upvotes: 3

Related Questions