danwoods
danwoods

Reputation: 4907

working with 'this' and jQuery

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?

Upvotes: 0

Views: 119

Answers (3)

EmKay
EmKay

Reputation: 1089

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");

  });

});

Upvotes: 1

Joe D
Joe D

Reputation: 3708

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)" />

Upvotes: 1

Jonathan Fingland
Jonathan Fingland

Reputation: 57197

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.

Upvotes: 4

Related Questions