Dan Abbitt
Dan Abbitt

Reputation: 13

jQuery changing an image on hover, then maintain image on click

I'm at a bit of a problem with jQuery and an image.

I'm trying to create a simple system where an image changes on hover (which I've successfully made work with jQuery .hover()) however I'm now trying to set it up so if the user clicks on the image, the source is permanently changed to the hover image.

The problem I'm having is when I click, the source changes but when I hover off it changes back to the "off" image! Such a simple problem but I can't find a solution.

The hover code:

$("#image").hover(function () {
            $(this).attr("src", getImageSourceOn("image"));
        }, function () {
            $(this).attr("src", getImageSourceOff("image"));
});

The functions getImageSourceOn / Off simply return a string based on the parameter with the new source.

The onClick code:

var imageSource = $(imageID).attr("src");
  var onOff = imageSource.substring((imageSource.length - 5), (imageSource.length - 4));
  if (onOff == "F")
  {
    //alert("Off\nstrID = " + strID);
    $(imageID).attr("src", getImageSourceOn(strID));
  }
  else
  {
    //alert("On");
    $(imageID).attr("src", getImageSourceOff(strID));
  }

This code just takes the source and looks for On / Off within the source to put the opposite as the image. I tried using .toggle() instead of this substring method but I couldn't get it to work.

Upvotes: 1

Views: 3318

Answers (1)

Rolando Cruz
Rolando Cruz

Reputation: 2784

Declare a global variable. Attach a function on the click event:

var clicked = false;

$("#image").click(function(){
  if(!clicked)
    clicked = true;
  else
    $(this).attr("src", getImageSourceOff("image"));
});

Then modify you hover code

  $("#image").hover(function () {
      $(this).attr("src", getImageSourceOn("image"));
  }, function () {
     if(!clicked)
       $(this).attr("src", getImageSourceOff("image"));
  });

Upvotes: 2

Related Questions