wood burning stoves 2.0*
The moose likes HTML, CSS and JavaScript and the fly likes JQuery:- Adding event to element not present currrently Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "JQuery:- Adding event to element not present currrently" Watch "JQuery:- Adding event to element not present currrently" New topic
Author

JQuery:- Adding event to element not present currrently

Praful Thakare
Ranch Hand

Joined: Feb 10, 2001
Posts: 640
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


All desirable things in life are either illegal, banned, expensive or married to someone else !!!
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

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.


GenRocket - Experts at Building Test Data
Praful Thakare
Ranch Hand

Joined: Feb 10, 2001
Posts: 640
okies, thanks much.

-P
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61448
    
  67

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 ]

[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61448
    
  67

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

Joined: Feb 10, 2001
Posts: 640
you the man Bear.
 
wood burning stoves
 
subject: JQuery:- Adding event to element not present currrently