1

I want when I click in the image I get the new but after 1 second I want to get the default. I added the function setTimeout(), but after one second I still have the same image (pressed.svg)

This is all my code :

 <html>
 <head>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script language='Javascript'> 

 $(document).ready(function(){

            $("#myImage").on("click",function() {

                $(this).attr("src","images/pressed.svg");
                setTimeout(function() {
                    $(this).attr("src","images/normal.svg");
                },1000);

            });

        });
        </script>
</head>
  <body>
      <img src="images/normal.svg" id="myImage">    
  </body>
</html>

2 Answers 2

2

The problem is that this in your anonymous function call refers to the wrong this. You need to assign the value of this in your handler to a temporary that will be used by the anonymous function:

$(document).ready(function() {
    $("#myImage").on("click",function() {
        var me = this;
        $(me).attr("src", "images/pressed.svg");
        setTimeout(function() {
            $(me).attr("src", "images/normal.svg");
        }, 1000);
    });
});

You could accomplish the same thing using just the DOM, since you aren't doing anything jQuery specific:

$(document).ready(function() {
    $("#myImage").on("click", function() {
        var me = this;
        me.src = "images/pressed.svg";
        setTimeout(function() {
            me.src = "images/normal.svg";
        }, 1000);
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

Demo : http://jsfiddle.net/

JS Fix :

 $(document).ready(function(){
        $("#myImage").on("click",function() {
            var $img = $(this);
            $img.attr("src","images/pressed.svg");
            setTimeout(function() {
                $img.attr("src","images/normal.svg");
            },1000);
        });

    });​

when you do $(this) in setTimeout, it wont work as there is no reference in settime out function. cache the element first and then use it in settimeout.

Comments

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.