Search code examples
javascriptjquerycolorbox

display alt attr after its own image


having a list of images with alt, i need to grab the content of the alt and display in a clikkable link just after its own image tag.

I already have done this and I did again in a simple code which works properly, but when it comes to make it work in the website i'm working on, i got some problem in the loop, and it show always the first alt.

Maybe someone of you can see what i'm missing here.. Note: I'm working in Drupal 7 with a Colorbox plugin. Maybe it matter

Here the code:

jQuery(document).ready(function($) {

  //GALLERY COLORBOX CAPTION

  var galleryContainer = jQuery('.field-items');
  jQuery('.field-item').find('img').addClass( "thumbs" );

  var imgGallery = jQuery(".thumbs");

  for(var i = 0; i < imgGallery.length; i++){
    var thisImg = jQuery(imgGallery[i]);
    var thisImgIndex = thisImg.index();
    console.log(thisImgIndex)
    var thisImgAlt = jQuery(imgGallery).attr('alt');
    var thisImgTitle = jQuery(imgGallery).attr('title');

    thisImg.parent().parent().find("a")
      .eq(thisImgIndex).after('<div class="alt-link"> <a href="' + thisImgTitle + ' " target="_blank" >' + thisImgAlt + ' </a></div>');

  }

});

The html is bit messy but the most important part are:

<div class="field-items">

<div class="field-item even">
  <a   href="http://loungesquatt.com/drupal734/sites/default/files/styles/gallery_large/public/MemoryLoss_eFlyer.jpg?itok=Md01BlUj" title=" Memory Loss 2014 Berlin (de)" class="colorbox init-colorbox-processed cboxElement" rel="gallery-node-44">

<img typeof="foaf:Image" src="http://loungesquatt.com/drupal734/sites/default/files/styles/gallery_thumb/public/MemoryLoss_eFlyer.jpg?itok=fqMdCKg7" width="200" height="200" alt="http://www.dw.de/memory-loss-sarkozys-berlin-wall-blunder/a-4878717" title=" Memory Loss 2014 Berlin (de)" class="thumbs"></a>
  <div class="alt-link"> 
    <a href=" Memory Loss 2014 Berlin (de) " target="_blank">http://www.dw.de/memory-loss-sarkozys-berlin-wall-blunder/a-4878717 </a>
  </div>
</div>

<div class="field-item even"> ... </div>

<div class="field-item odd">... </div>

<div class="field-item even">...</div>

</div> 

For better understanding you can inspect the site: http://loungesquatt.com/drupal734/content/graphics


Solution

  • You are only selecting the first element in this code jQuery(".thumbs");

    Use something like

    var thisImgAlt = imgGallery.eq(i).attr('alt');
    

    inside the loop