1

I have an image scroller set up, and I keep a count of the current item through a variable called current_item. Now, I want to display the alt text of the image in a list of images whose index matches the item_count.

Here's the JQuery

var scroll_text = $('#ax_campaign_content li').index(current_item).children('img').attr('alt');
$('#ax_campaign_scroller h4').text(scroll_text);

And this is the basic html structure:

<div id="ax_campaign_content">
    <ul>
    <li><img alt="Image 1"></li>
    <li><img alt="Image 2"></li>
</ul>
</div>

<div id="ax_campaign_scroller">
    <h4>Image Text Goes Here</h4>
</div>

This is what I'm trying to do but it's not working. Anybody see where I'm going wrong?

mheavers
  • 29,530
  • 58
  • 194
  • 315
  • I didn't have any luck with the eq method below. But on second thought - why would I have to even loop through all the items? Couldn't I just use the revised code above - and somehow select the alt text of an item with the index in the list that matches the current_item value? – mheavers Jan 29 '11 at 15:03

3 Answers3

3

Your code will iterate the li elements and then iterate the images inside of that li, which will always be just one image. So what you're doing will never get anything related to the current_item variable.

Instead you might want to try passing current_item to .eq to first get the li element with that index, and then get the image alt attribute:

var scroll_text = $("#ax_campaign_content li")
    .eq(current_item)
    .find("img").attr("alt");

$("#ax_campaign_scroller h4")
    .text(scroll_text);

Or you can do it with a one-liner (added new-lines and tabs for readability) and select the image in the same selector without using .find:

$("#ax_campaign_scroller h4").text(
    $("#ax_campaign_content li:eq("+current_item+") img")
        .attr("alt")
);
mekwall
  • 28,614
  • 6
  • 75
  • 77
2

try eq method - http://api.jquery.com/eq/

$('#ax_campaign_content li img').eq(current_item).attr('alt');
jcubic
  • 61,973
  • 54
  • 229
  • 402
0

Your each is looping through each li element, so when you look for img within the each function you are looking inside the li:

$(this).children("img").index()

Will always return zero, since you only have 1 img inside each li.

Jquery .each already gives you the index, so you can just test that against your current_item like so:

$('#ax_campaign_content li').each(function(index) {
        if (index == current_item){
        scroll_text = $(this).children('img').attr('alt');
        $('#ax_campaign_scroller h4').text(scroll_text);
    }
});

Responding to the updated comment: You can always go for the one-liner!

$('#ax_campaign_scroller h4').text(
    $('#ax_campaign_content li').eq(current_item).children('img').attr('alt')
);
WSkid
  • 2,736
  • 2
  • 22
  • 26
  • Yeah you're right on the one-liner. I did do it like that to begin with, but thought this would be easier to understand if you split it up :) – mekwall Jan 29 '11 at 15:13