partlycloudy
partlycloudy

Reputation: 429

Hiding element after firing click handler

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(){ ... }

Upvotes: 0

Views: 102

Answers (3)

cgp
cgp

Reputation: 41381

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

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

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');
  }

Upvotes: 0

Olly Hodgson
Olly Hodgson

Reputation: 15785

$("#foo").click(function () {
    $(this).hide(); /* This refers to the item(s) being clicked */
})

Upvotes: 1

Related Questions