Adding elements with jQuery and then adding events to them

How to achieve that, 'cos this doesen't work

Page 1 of 1

2 Replies - 683 Views - Last Post: 30 April 2010 - 03:35 AM

#1 deemeetar  Icon User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 66
  • Joined: 22-January 10

Adding elements with jQuery and then adding events to them

Posted 29 April 2010 - 12:30 PM

$(":password").focus(function(){
    $(this).after("<img id='chromeBtn' src='chBtn.png' />");
});
//till here it works, after that it doesen't
$("#chromeBtn").click(function(){
    someFunc();
	});



How to make the second expression work? I don't have access to the html file i use this script on, so i have to find a way to do it through JS.

Is This A Good Question/Topic? 0
  • +

Replies To: Adding elements with jQuery and then adding events to them

#2 girasquid  Icon User is offline

  • Barbarbar
  • member icon

Reputation: 108
  • View blog
  • Posts: 1,825
  • Joined: 03-October 06

Re: Adding elements with jQuery and then adding events to them

Posted 29 April 2010 - 02:58 PM

I tend to do this by creating the element I want to add with jQuery, and attaching the handlers before I put it anywhere:
$(":password").focus(function(){
	var $btn = $("<img id='chromeBtn' src='chBtn.png'>");
	$btn.click(function() {
		someFunc();
	});
	$(this).after($btn);
});


Alternately, if your code to bind to #chromeBtn is scoped the way it looks to be, your issue might be that the object doesn't exist when you bind to that handler - in that case, take a look at jQuery's [url=http://api.jquery.com/live/].live[url] operator, or bind your event after adding the object to the DOM.
Was This Post Helpful? 0
  • +
  • -

#3 deemeetar  Icon User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 66
  • Joined: 22-January 10

Re: Adding elements with jQuery and then adding events to them

Posted 30 April 2010 - 03:35 AM

.live helped me a lot. Thank you.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1