0

I want just when I click on the image I see the new image and just after the click I want the new image changes with the default one, but I have to drag the mouse to see the default image but I don't want that.

This is my code:

$(document).ready(function(){
    $(".img-button").live('click', function () {
           $(this).attr("src","images/pressed.svg");
    }); 
});
4
  • FYI: live is deprecated in jQuery 1.7+ Commented Oct 12, 2012 at 16:50
  • So when you click on the image it changes to a different image. You than want the image to change back to the original source when you move the mouse? Commented Oct 12, 2012 at 16:51
  • no epascarello, I want to see the new image only in the click action and then it disappears and the default image replaces the new. Commented Oct 12, 2012 at 16:54
  • Could you post your HTML Code Commented Oct 12, 2012 at 17:14

1 Answer 1

3

If you only have one image, I suggest you give it an ID instead of (ab)using the classname. If you have several and use the same image for all, then change $("#myImage") below to $(".img-button")

Toggle

$(document).ready(function(){
    $("#myImage").toggle(
     function() {
       $(this).attr('src','images/pressed.jpg');
     },
     function() {
       $(this).attr('src',"images/default.jpg");
    });
});

Swap after leaving

$(document).ready(function(){
    $('#myImage').on("click",function() {
       $(this).attr('src','images/pressed.jpg');
    });
    $('#myImage').on("mouseleave",function() {
       $(this).attr('src',"images/default.jpg");
    });
});

Swap half a sec after pressing

$(document).ready(function(){
    $('#myImage').on("click",function() {
       $(this).attr('src','images/pressed.jpg');
       setTimeout(function() {
         $('#myImage').attr('src',"images/default.jpg");
       },500);
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

setTimeout not working for me, I have all time the pressed image.
Try mouseup instead of click with the timeout
Or if you want to change back even if they keep holding the mouse, try mousedown

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.