Chad Chad - 4 months ago 7
jQuery Question

jQuery slider index

I'm trying to duplicate the text inside the

<h1>
tag in the
.slider-item
divs to the anchor tags in the
.bx-pager
div. For example, the anchor in the first
.bx-pager-item
should have the text of the h1 in the first .slider-item div. Then the anchor tag in the second
.bx-pager-item
should have the text of the
<h1>
in the second
.slider-item
div. Is there something wrong with my jQuery code that makes it not do what I want?

My jQuery code:

$(window).load(function(){
$("#pagination .bx-pager-item").each(function(){
var whichPos = $(this).index();
var whichSlide = $('.slider-item').index(whichPos).find('h1').text();
$(this).find('a').text(whichSlide);
});
});


The pagination:

<div id="pagination">
<div class="bx-pager-item"><a href="#"></a></div>
<div class="bx-pager-item"><a href="#"></a></div>
<div class="bx-pager-item"><a href="#"></a></div>
</div>


The slider structure is:

<div class="bxslider">
<div class="slider-item">
<h1>Header</h1>
</div>
<div class="slider-item">
<h1>Header 2</h1>
</div>
<div class="slider-item">
<h1>Header 3</h1>
</div>
</div>

Answer

Change:

var whichSlide = $('.slider-item').index(whichPos).find('h1').text();

to:

var whichSlide = $('.slider-item').eq(whichPos).find('h1').text();

index does not get the nth element, it returns a number.

CodePen: http://codepen.io/theblindprophet/pen/JKLbXw