Slevin
Slevin

Reputation: 312

Pulling alt's value

I am looking to use Javascript or jQuery to pull the alt tag from the specific image that had been clicked in the HTML and copy its value into a caption field.

function change_image(diff){
  var newAlt = $(this).attr('alt');
  position = (position + diff + hrefs.length) % hrefs.length;
  revealImage(hrefs[position]);
  $nav.find('.counter').html(newAlt);
}

That is what I have so far and it does not work.

Upvotes: 1

Views: 1176

Answers (1)

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827366

You are using the this keyword inside your function, it will refer to the element that triggered the event if you bind it like this:

$('img').click(change_image);

But since you have an argument in your function, I think that you are invoking it with a normal function call, in that way, the context (the this keyword) is not preserved, you can:

$('img').click(function () {
  change_image.call(this, 5); // preserve the context and pass a diff value
});

Upvotes: 1

Related Questions