0

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?

danwoods
  • 4,572
  • 11
  • 56
  • 84

3 Answers3

4

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 What underlies this JavaScript idiom: var self = this? 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.

Community
  • 1
  • 1
Jonathan Fingland
  • 53,185
  • 11
  • 81
  • 77
1

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
  • 3,328
  • 2
  • 16
  • 14
1

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
  • 1,069
  • 1
  • 12
  • 28