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?
Asked
Active
Viewed 114 times
3 Answers
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
- 56,385
- 11
- 85
- 79
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,588
- 2
- 19
- 14
-
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 Oct 16 '09 at 08:47
-
would I reference that like: $(el).src("images/16-arrow-down.png"); ? – danwoods Oct 16 '09 at 22:52
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,089
- 1
- 13
- 28