1

So I'm trying to get the number of the li that I click and show the corresponding page text while hiding the others. (labeled #text1, #text2, #text3 etc...), but the code below isn't doing anything for me.

Help is greatly appreciated!

var j = 0;
$(".gallery li").each(function () {
    j++;

    $(".gallery li").click(function () {
        var num = $(this).index() + 1;
        $('#text' + num).addClass('currentpage');
        $('#text' + num).siblings().removeClass('currentpage');
    });
});
Joe
  • 15,205
  • 8
  • 49
  • 56
jaruesink
  • 1,205
  • 2
  • 14
  • 24

3 Answers3

3

See this working fiddle. You just need to take out the .each

$(".gallery li").click(function () {
    var num = $(this).index() + 1;
    $('#text' + num).addClass('currentpage');
    $('#text' + num).siblings().removeClass('currentpage');
});
Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
  • Like the others said, you don't need `$('#text' + num)` or `$('#text' + num)`, it could just be `$(this)` – Zach Saucier Jun 27 '13 at 19:59
  • Well, I might be wrong, but from the OPs description, #text1, etc., are elsewhere on the page, so $(this) can't be used. – Andy G Jun 27 '13 at 20:04
2

Try

var num = $('li').index(this) + 1;

instead of

var num = $(this).index() + 1;

And remove the each loop

$(".gallery li").click(function () {
     var num = $('.gallery li').index(this) + 1;
     $('#text' + num).addClass('currentpage');
     $('#text' + num).siblings().removeClass('currentpage');
});

Should be good enough

And better .. You need not use the index in the first place

$(".gallery li").click(function () {
    $(this).addClass('currentpage');
    $(this).siblings().removeClass('currentpage');
});

You can just use the this context directly in your code as that corresponds to the current li that is selected.

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • If there are other `li` before this set, then the index will likely be incorrect won't it? (I haven't tested.) Perhaps `$('.gallery li').index(this)` – Andy G Jun 27 '13 at 19:43
  • sure.. That will be a better selector... :) – Sushanth -- Jun 27 '13 at 19:45
  • 1
    The original `var num = $(this).index() + 1;` works for me in jsFiddle - I think it was just the use of `each()` that was the problem. – Andy G Jun 27 '13 at 19:49
  • I think the #text1, etc., are elsewhere on the page, so we can't use $(this). – Andy G Jun 27 '13 at 19:57
0

I'm not sure what you're doing... but you can do this:

Throw in index and value as the parameters of the closure for each. Example: $(".gallery li").each( function(index, value){ - then you can use index instead of j

Rob W
  • 9,134
  • 1
  • 30
  • 50