Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Pass index to function

Hello,

I'm wondering if anyone can help me here. Learning JS and haven't quite got my head around it yet yet. I have a script that i'm running that delays the loading of a set of modal galleries by only loading them when called.

//When an link with a class of .commercial-thumb is clicked
$(document).on('click', '.commercial-thumb', function () {
//variable index is the index of the links parent 'li'
var index = $(this).parent('li').index();
 // Find iFrames of all .comm-gallery elements and alter their src to iframes data-src value
 $('.comm-gallery').find("iframe").prop("src", function(){
    // Set their src attribute to the value of data-src
    return $(this).data("src");
    });
});

This works fine, but it loads ALL the galleries with a class of comm-gallery. What I would like to do is to only target the .comm-gallery with the same index as the variable index.

I know the solution should be quite simple as its only passing the value of a variable to the index of a class being called, but i'm coming up short! I've tried a number of different ways I thought this might be possible but i'm coming up short as I only started learning JS a few weeks ago.

Thanks in advance for any help you guys can give.

1 Answer

Solved:

//When an link with a class of .commercial-thumb is clicked
$(document).on('click', '.commercial-thumb', function () {
      //variable index is the index of the links parent 'li'
      var index = $(this).parent('li').index();
     // Find iFrames of all .comm-gallery elements and alter their src to iframes  data-src value
        $('.comm-gallery').find("iframe")eq.(index).prop("src", function(){
        // Set their src attribute to the value of data-src
        return $(this).data("src");
        });
   });