Search code examples
jqueryimageindexingeachscroller

Finding an item with JQuery whose index matches a count variable


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?


Solution

  • 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")
    );