views:

29

answers:

2

I have some elements inside an UpdatePanel which may or may be displayed, depending on various conditions.

<asp:UpdatePanel ID="MyUpdatePanel" runat="server">
    <ContentTemplate>
        <asp:Panel ID="MyPanel" runat="server">
            <img id="clickableImage" src="/path/to/image.png" alt="Clickable Image" />
            <span id="specialMessage">You clicked on the image!</span>
        <asp:Panel>
    </ContentTemplate>
</asp:UpdatePanel>

I'm trying to wire it up so that the specialMessage SPAN is shown when the clickableImage IMG is clicked with the following:

$(document).ready(function() {
    $("#clickableImage").click(function() {
        $("#specialMessage").show();
    });

    $("#specialMessage").draggable();
});

However, since MyPanel is often not visible when the page loads (but it may be visible later based on user interaction), the events aren't hooked up. Is there a way that I can hook up these events even if MyPanel is not visible on the initial page load?

+5  A: 

Use the $.live() method to attach the logic for dynamically-added elements.

$("#clickableImage").live("click", function() {
    $("#specialMessage").show();
});

This will apply to all present instances of #clickableImage as well as all future instances too.

Jonathan Sampson
Using live() in .ready() is ok? And if I wanted the specialMessage SPAN to use ui.draggable?
Bullines
Yes it is. If fact its the ideal place to use it :-)
James Wiseman
Not so ideal indeed. See http://stackoverflow.com/questions/2024018/using-domcontentready-considered-anti-pattern-by-google
thorn
+1  A: 
Ed Woodcock

related questions