kidwon
kidwon

Reputation: 4524

.index() problem

You see I'm trying to manipulate some elements when comparing their index. The problem is my index isn't assigned with int value but stays undefined.

$(function(){
  var i;
  $("a").click
  (
    function()
    {
      i = $("a").index(this);                     
      $(".textholder div:eq(i)").slideUp();
      $(".textholder div:eq(i+1)").css('top', '-210px');
      return false;
      }
  );
  alert(i);
});

I'm also open for any remarks about my syntax and algorithm!

Any suggestions? Thank you all

Upvotes: 1

Views: 111

Answers (3)

Skilldrick
Skilldrick

Reputation: 70819

You alert i before anything is clicked. When you click something, the only bit that's executed is from the line function() to the line return false; So it's no wonder that i is undefined.

If you want to see the value of i when it is set, move the alert(i) line (or even better, change it to console.log()) to below the i = $("a").index(this); line.

Upvotes: 4

Orbling
Orbling

Reputation: 20602

The i variable will not get interpolated within the string, bring it outside.

$(function(){
  var i;
  $("a").click
  (
    function()
    {
      i = $("a").index(this);                     
      $(".textholder div:eq(" + i + ")").slideUp();
      $(".textholder div:eq(" + (i+1) + ")").css('top', '-210px');
      return false;
      }
  );
  alert(i);
});

Upvotes: 2

David Thomas
David Thomas

Reputation: 253318

I'm not sure that it's your only problem, but:

$(".textholder div:eq(i)").slideUp();
$(".textholder div:eq(i+1)").css('top', '-210px');

Should be:

$(".textholder div:eq(" + i + ")").slideUp();
$(".textholder div:eq(" + i+1 + ")").css('top', '-210px');

Otherwise the i won't be evaluated.

Upvotes: 5

Related Questions