tags:

views:

30

answers:

1

HI al

I'm trying to allow a kind of 'toggle' state on a bunch of image elements, whereby they have

  • a rollover,
  • an onclick image change and
  • List item an ID change when clicked.

That much I can do, but I can't get them to revert when they are clicked a second time (i.e. returning to the original image, with the rollover re-instated and the original ID restored).

Here's my code:

$("#Table1 img").each(function () { // loops round every image in Table1
    $(this).hover(function () {   // sets hover rules
        this.src = "images/mine.gif"
    },function () {  // mine.gif for mouseover, available.gif for mouseout
        this.src = "images/available.gif"
    });
    $(this).click(function () { // sets click rules
        this.src = "images/mine.gif"; // mine.gif for onclick
        this.id = "x" + this.id; // adds an 'x' to the ID of clicked images
        $(this).unbind("mouseover mouseout"); // removes mouseover and mouseout events to keep visual selection
        $(this).click(function () {
            this.src = "images/available.gif";
            this.id = this.id.substr(2, this.id.length);
        });
    });
});

I tried embedding a $(this).hover() function in the second $(this).click(), but that didn't work.

The above code works entirely, but I just can't get the original rollovers to be reinstated.

Any help would be much appreciated. I realise there are more elegant ways of doing what I've already done in jQuery (delegates and such like) but since I'm learning I'd like to do it the simple and obvious way first.

:)

A: 

I was able to do this by using the class to maintain the state of the image click. The hover doesn't have to be removed, simply check against the state of the image before executing whatever code sits inside the hover functions. I also used .toggle() instead of trying to nest .click() listeners.

http://jsfiddle.net/e8CdP/

Brian Flanagan
That works like a charm! Thank you :)Now I just need to work out what toggle() does and I'll be sorted :)
melat0nin
.toggle() is just like .hover() except it's used for the click event.
Brian Flanagan