Steven Tomko
Steven Tomko

Reputation: 98

Change image when is clicked on it, and then change it back

I'm having problem, I can't figure out how to change image back when it's not clicked on it.. When user click on image, it shows the image that is supposed to. But, I want to change the image back after click... How can be this done? Now, when you click on image, it changes, but stays on the clicked image and changes to default one only if your mouse is not on that image..

My code..

<img src="pictures/fbutt.jpg" width="640" height="360"
onmouseover="this.src='pictures/fbuttho.jpg'"
onmouseout="this.src='pictures/fbutt.jpg'" onclick="this.src='pictures/fbuttac.jpg'"/>

Upvotes: 0

Views: 310

Answers (3)

Dipen Dedania
Dipen Dedania

Reputation: 1450

For example your HTML is something like this..

<img id="pic" src="pictures/fbutt.jpg" width="640" height="360"/>

Assign an id to it and bind jQuery mouseup and mousedown events on that.

<script>
$(document).ready(function(){
    $("#pic")
      .mouseup(function() {
          $( this ).attr('src','pictures/fbuttac.jpg' );
      })
      .mousedown(function() {
          $( this ).attr('src','pictures/fbutt.jpg' );
      });
});
</script>

Upvotes: 0

lionheart98
lionheart98

Reputation: 968

Have a look at this little demo using jquery: https://jsfiddle.net/fodxvssn/

$(document).ready(function()
{
    $("#img").mouseup(function() 
    {
        $(this).attr("src", "http://cdn.sstatic.net/stackoverflow/img/[email protected]?v=ea71a5211a91");
    });

    $("#img").mousedown(function()
    {
        $(this).attr("src", "https://i.sstatic.net/CE5lz.png");
    });
});

Upvotes: 1

iurii
iurii

Reputation: 4230

Try this

<img id="testImage" src="http://i.huffpost.com/gen/964776/images/o-CATS-KILL-BILLIONS-facebook.jpg" alt="..." width="300" height="300" />

<script>
  var imageEl = document.getElementById('testImage');
  var newImg = 'http://www.mycatspace.com/wp-content/uploads/2013/08/adopting-a-cat.jpg';
  var defaultImg = imageEl.src;

  imageEl.onmousedown = function() {
    this.src = newImg;
  }

  imageEl.onmouseup = function() {
    this.src = defaultImg;
  }
</script>

Upvotes: 0

Related Questions