1

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.

Slevin
  • 312
  • 2
  • 12
  • 1
    using "attr" to retrieve alt value from an image and "html" to display the value seems to be correct. What and where exactly is your problem? – ybo Sep 18 '09 at 16:00
  • The code that I have posted does not pull the alt tag. When I run my page, the content area where the alt tag should be displayed is empty. I am unsure where exactly the problem lies. I will try to run a simple Alert to see if it is at least pulling the alt value. Maybe this will help me pinpoint if the issue is with the retrieval of the alt value or the posting of the value. – Slevin Sep 18 '09 at 18:23
  • Okay. My Alert returned an 'undefined' value. So the issue must lie in the alt tag retrieval. – Slevin Sep 18 '09 at 18:25
  • Could you post some more code? How do you call your `change_image` function. – Christian C. Salvadó Sep 18 '09 at 20:31

1 Answers1

1

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
});
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • I am now using this line: var newAlt = $.attr($('img').get(0),'alt'); It retrieves the alt tag of one static image and I have been unable to use the (this) feature to pull the alt tag of the specifically clicked image. Any advice? – Slevin Sep 18 '09 at 19:41