views:

55

answers:

3

Say I have the following code to add a clickable image after a set of elements. The click handler fires every time the image is clicked which is not what I want. I guess hiding the image using .hide() in the click handler is one approach but I can't figure out how to refer to the img element in the click handler.

Help? Thanks

  $(...)
  .after($('<img src="..."/>')
  .css("cursor","pointer")
  .attr("title","Click here for ...")
  .click(function(){ ... }
A: 

You could give your image an unique id in order to fetch it:

$(...)
  .after($('<img id="myimage" src="..."/>')
  .css("cursor","pointer")
  .attr("title","Click here for ...")
  .click(function()
  { 
      var img = $('#myimage');
  }
Darin Dimitrov
The *this* in this case refers to the elements which were selected to append html after - the img src is what's being added, that's why this ends up being not straight-forward.
altCognito
I didn't realize that jQuery alters the context of "this" so intuitively and jQueri-fies it by wrapping it in $(this)! This is a really well designed library. Thanks!
VANJ
Are you sure? As per http://www.learningjquery.com/2007/08/what-is-this the "this" in any click handler refers to the DOM element for which the click handler is being written.
VANJ
VANJ - Precisely.
altCognito
+1  A: 

It would probably be simplest and most readable to break it into two lines:

var e = $('<img src="..."/>');
  $(...)
  .after(e)
  .css("cursor","pointer")
  .attr("title","Click here for ...")
  .click(function(){ ... use e here...  }

Although you could use next as I did in this example aka:

$('p')
  .after($('<img src="..."/>'))
  .css("cursor","pointer")
  .attr("title","Click here for ...")
  .click(function() { 
      $(this).next().css("border", "solid white 5px");

  })

So that uses the niceness of this to fetch the element you are looking for without any temporaries. http://jsbin.com/ulewo

altCognito
I goofed up the first link, this one works.
altCognito
+1  A: 
$("#foo").click(function () {
    $(this).hide(); /* This refers to the item(s) being clicked */
})
Olly Hodgson