tags:

views:

65

answers:

3

Hello all. I'm trying to use the 'this' keyword to work with jQuery. I'm trying to rotate an image when it's clicked by passing 'this' as a parameter in it's onclick function. How would I then reference the image using jQuery?

+4  A: 

before passing the anonymous function to your click handler, do

var self = this;

and change the references to this in your handler to self

See http://stackoverflow.com/questions/962033/what-underlies-this-javascript-idiom-var-self-this/962040#962040 For an example in the question.

To quote:

function Note() {
  var self = this;

  var note = document.createElement('div');
  note.className = 'note';
  note.addEventListener('mousedown', function(e) { return self.onMouseDown(e) }, false);
  note.addEventListener('click', function() { return self.onNoteClick() }, false);
  this.note = note;
  // ...
}

basically, when the event handler actually calls the function, the context has changed -- this no longer refers to the same object you thought it did. We get around this by using a non-special variable name, self which the function retains visibility of due to closure.

Jonathan Fingland
+1  A: 

If you pass the element (this) through to a function via onclick, you can just wrap the jQuery function ($) around it to treat it like a jQuery object.

<script type="text/javascript">
    function myfunction(img) {
        var el = $(img);
        // Some other code
    }
</script>

<img src="someimage.jpg" alt="" onclick="myfunction(this)" />
Joe D
I think that's the exact answer I was looking for. If that's the case I'll be sure to accept your answer :)
danwoods
would I reference that like: $(el).src("images/16-arrow-down.png"); ?
danwoods
nevermind, got it. Thanks again!
danwoods
+1  A: 

To reference the image clicked and change it's src-attribute you do like this:

$(document).ready(function() {

  $("img").click(function() {

    var $this = $(this); //For performance

    $this.attr("src","NewImgSrc.jpg");

  });

});
EmKay