I am trying to access an image that is passed into an event handler using this in jQuery.
So “this” in this case would be a div or li that contains an img tag within the div or li.
I’ve tried the follow accessors:
$(this).attr(),
$(this).(‘.imgClassName’).attr(),
$(this: img).attr(),
$(this.imgClassName).attr()
and none of those worked. Here is my script:
var closedText = 'Show All';
var openedText = 'Hide All';
var helpExpand = '/images/expand.png';
var helpCollapse = '/images/collapse.png';
$('li.helpList: a').click(function () {
$(this).next().slideToggle('fast', function () {
if (faqClosed) {
$(this).attr({
src: helpExpand,
title: openedText,
alt: openedText
});
} else {
$(this).attr({
src: helpCollapse,
title: closedText,
alt: closedText
});
}
});
return false;
});
This does not work. However, this does work (for my Hide/Show all):
$('#showAll').click(function () {
if (faqClosed) { // closed
$('li.helpList: div').show('fast'); faqClosed = false;
$('#showAll').text(openedText);
$(".helpToggle").attr({
src: helpExpand,
title: openedText,
alt: openedText
});
} else { // opened
$('li.helpList: div').hide('fast'); faqClosed = true;
$('#showAll').text(closedText);
$(".helpToggle").attr({
src: helpCollapse,
title: closedText,
alt: closedText
});
}
return false;
});
$(‘li.helpList: div’) is the container for an open/closed item. Within that is an img tag with a little arrow. Here is the HTML for a container:
<li class="helpList">
<a href="#">
<img src="/images/collapse.png" class="helpToggle" alt="Contraer" />How do I do stuff?
</a>
<div class="helpContent">To do stuff, please do something.</div>
</li>
[UPDATE]
Here is my test script, which alerts open or close depeneding on the state. This currently works, but it still can not find the image (the collapse/expand.png file does not hide, and it never changes)
// Wire up hide/show to a.click event:
$('li.helpList: a').click(function () {
$(this).next().slideToggle('fast', function () {
if (faqClosed) {
alert('closed');
$(this).find('.helpToggle').hide();
$(this).find('img').attr({
src: helpExpand,
title: openedText,
alt: openedText
});
faqClosed = false;
} else {
alert('open');
$(this).find('.helpToggle').show();
$(this).find('img').attr({
src: helpCollapse,
title: closedText,
alt: closedText
});
faqClosed = true;
}
You start with an
atag. You call.next()which gets the next sibling (thediv) and then callslideToggle()on that.thisin that context is thediv, which doesn’t contain the image.If you want to search within the
atag, store a reference to it before you callslideToggle(), then use it as the context (second parameter) for your selector.Here’s a working demo to illustrate it (apologies for the image, it’s the only one I had available).