views:

97

answers:

2

Hi,

I want to extend some JQuery code to replace an image once I click on it. I have this:

var minimiseContent = function(e)
{
    var targetContent = $('div.itemContent', this.parentNode.parentNode);
    if (targetContent.css('display') == 'none') {
        targetContent.slideDown(300);
        var minIcon = $('minimise', this.parentNode.parentNode);
        $(minIcon).attr("src", "../IMG/btnMinimise.png");

    } else {
    targetContent.slideUp(300);
        var minIcon = $('minimise', this.parentNode.parentNode);
        $(minIcon).attr("src", "../IMG/btnMaximise.png");

    }
    return false;
};

which is called from this:

$('a.minimise').bind('click', minimiseContent);

and declared like so:

<a href="#" class="minimise"><img src="../IMG/btnMinimise.png" class="minimise" /></a>

Essentially the two lines in the first part of the coding should handle it i.e.

var minIcon = $('minimise', this.parentNode.parentNode);
            $(minIcon).attr("src", "../IMG/btnMinimise.png");

and

        var minIcon = $('minimise', this.parentNode.parentNode);
        $(minIcon).attr("src", "../IMG/btnMaximise.png");

But I do not know why the image is not replaced. minimise is a class in the css file. The rest of the coding works.

I have tried replacing $(minIcon) with $(this), $(img.minimise), but none work. Does anyone know of any solutions?

+2  A: 

My first impression is that you want to replace this:

var minIcon = $('minimise', this.parentNode.parentNode);

With this:

var minIcon = $('img.minimise', this.parentNode.parentNode);
drs9222
Cheers. I thought I already tried this - as written in my intial post - but it happened to work. Thanks
waqasahmed
A: 

You don't need the <a> tag. The img tag can have a click event as well.

Also, I think this is a good use case for the toggle function:

$("img.minimise").toggle(
  function () {
    $(this).attr("src", "../IMG/btnMinimise.png")
  },
  function () {
    $(this).attr("src", "../IMG/btnMaximise.png");
  }
);

It will alternate function calls on every click.

John Sheehan
Thanks, but I find the behaviour of the toggle is unpredictable. I am using jQuery 1.1.2 so maybe that is the problem? But I can't upgrade. The behavious for instance does many sliding up, and sliding down on one click. Is it possible through the way it is coded in my initial code?
waqasahmed
actually drs9222 has solved it.. thanks again though
waqasahmed