Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JQuery:- Adding event to element not present currrently

 
Praful Thakare
Ranch Hand
Posts: 642
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I want to attach an event on mouseover of image that gets added dynamically.

if i do this in Onload the event is not getting attached as the image does not exists when onload is fired.

so question is how can we attach events in Onload function to items those get added after onload is fired?

I read this in JQ in Action books, but unable to trace it now


-P
 
Gregg Bolinger
GenRocket Founder
Ranch Hand
Posts: 15302
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'll need to add the event after the image is added to the DOM. Note that only the IMG tag has to exist. The fact that the image itself has or has not been pulled from the server yet doesn't matter.

So the key here is to tie into the behavior of the images being added and then add your event to those images. Not everything in jquery is done onload.
 
Praful Thakare
Ranch Hand
Posts: 642
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
okies, thanks much.

-P
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64631
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The LiveQuery plugin is what you want!

With LiveQuery you can establish "match" handlers to fire off when a matching object comes into existence, and when it goes out of existence. You can also establish event handlers on element that don't exist yet!

This is perfect for an Ajax environment where elements are popping in and out right and left. You can establish all your behavior up-front, and not have to worry about it later!
[ September 18, 2008: Message edited by: Bear Bibeault ]
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64631
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
P.S. In jQuery in Action, it's covered in the chapter on plugins! (Section 9.3, to be exact)
[ September 18, 2008: Message edited by: Bear Bibeault ]
 
Praful Thakare
Ranch Hand
Posts: 642
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you the man Bear.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic