Skip to content Skip to sidebar Skip to footer

Get Number Of Items By Class Within Parent In Js

I have built an image gallery where there is one main image and up to 5 thumbnails under it. and can use left and right buttons to cycle through the thumbnails and replace the main

Solution 1:

The most common approach for multiple instances is to look up to the container instance and then use find() within that instance.

Also when you look for the same selector multiple times it is best to store a reference to it rather than search the DOM every time you need to access it. It also makes the code a little easier to read

Something like:

$(".gallery-btn-left").unbind("click").bind("click", function() {
  var$gallery = $(this).closest('.MAIN-GALLERY-CLASSNAME'),
      $mainImg = $gallery.find(".gallery-main-image img"),
      $thumbs = $gallery.find('.gallery-thumbnail img'),        
      image_id = $mainImg.attr('data-id');

  image_id--;
  if (image_id == 0) {
    image_id = $thumbs.length;
  }
  var image_url = $thumbs.filter("[data-id=" + image_id + "]").attr('src');
  $mainImg.attr({'src': image_url, 'data-id',image_id});

});

Post a Comment for "Get Number Of Items By Class Within Parent In Js"