CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Handling or Attaching Events to Dynamically inserted HTML using jQuery in ASP.Net

By Satheesh Babu
Posted On Nov 11,2010
Article Rating:
Be first to rate
this article.
No of Comments: 0
Category: jQuery/ASP.Net
Print this article.

Handling or Attaching Events to Dynamic HTML using jQuery in ASP.Net

 

The introduction of jQuery library made the client scripting faster and simpler in the world of web development. The client side scripting which is once considered as complex has become simpler because of jQuery library. Understanding this, Microsoft has also taken several initiatives to support the development of jQuery library like providing jQuery intellisense support in visual studio, including jQuery library in the default project templates, etc.

If you are new to jQuery library, then I recommend you to take a look into the below FAQ for a quicker understanding,

What is jQuery? How to use it in ASP.Net Pages?

Moving forward, we will see how to attach event handlers to dynamically inserted html contents.

As we know, it is very simple to handle an event for a HTML control using jQuery. For example, the below jQuery code will attach an onclick event which will alert the user with the value of html button user when clicked.

<script src="scripts/jquery-1.4.2.min.js" type="text/javascript"></script>   

    <script type="text/javascript">

        $(document).ready(function() {

            $("#clickMe").click(function() {

                alert($(this).val());             

            });          

        });

    </script>  

</head>

<body>

    <form id="form1" runat="server">

    <div>

<input type="button" id="clickMe" value="Click ME"/>

 

At times, we will have requirements where we need to add HTML controls/contents dynamically and handle the events raised by those dynamic HTML controls. Consider the below code,

<script src="scripts/jquery-1.4.2.min.js" type="text/javascript"></script>   

    <script type="text/javascript">

        $(document).ready(function() {

            $("#clickMe").click(function() {              

                $("#dvDynamic").append("<a class=dynamiclink href=#>dynamic link</a><br>");

            });

         

        });

    </script>  

</head>

<body>

    <form id="form1" runat="server">

    <div>       

        <input type="button" id="clickMe" value="Click ME"/>

        <div id="dvDynamic">

         <b>Div Containing Dynamic Links:</b><br />

        </div>   

    </div>

    </form>

</body>

</html>

 

The above code will add a hyperlink inside the div(id= dvDynamic) whenever the button “Click Me” is clicked. Now, it is not possible to handle the events for these dynamic hyperlinks like we normally do with jQuery library.

Hence, the below code will not work for dynamic html controls.

            $("a.dynamiclink").click(function() {              

                $("#dvDynamic").append("<a class=dynamiclink href=#>dynamic link</a><br>");

            });

 

To tackle this, jQuery team has introduced a new method called live in jQuery version 1.3. You can use this live method to attach an event handler for all elements which match the current selector expression now and those getting added in future. Hence, this method can be used to attach events for dynamic added html controls.


Using live method in jQuery to bind events

 

How to add or hookup events with dynamic html using jQuery?

The below code snippet uses live method to hook up an event with the dynamically inserted HTML content.

    <script src="scripts/jquery-1.4.2.min.js" type="text/javascript"></script>   

    <script type="text/javascript">

        $(document).ready(function() {

            $("#clickMe").click(function() {             

                $("#dvDynamic").append("<a class=dynamiclink href=#>dynamic link</a><br>");

            });

 

            $("a.dynamiclink").live("click", function() {

                alert("Clicked dynamic link");

            });             

          

        });

    </script>  

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <input type="button" id="clickMe" value="Click ME"/>

        <div id="dvDynamic">

         <b>Div Containing Dynamic Links:</b><br />

        </div>   

    </div>

    </form>

</body>

</html>

 

When executed, the above code will alert with message “Clicked dynamic link” whenever the dynamic hyperlink is clicked.

 




Issues with live

Soon after, the live method caused lost of confusions and issues among the developer community due to the way it works.  Next section will help you understand this.

 

How it works?

The live method will attach a special event handler to the root document element ($(document)) instead of attaching the event to the actual matched element. By doing like this, whenever there is an event occurred in the dynamic element, the events get bubbled up to its parent in the DOM tree till it reaches the root (document) node.  The event handler of document (attached by live) will execute and this will check for a match if the event target of the bubbled up event is same the element specified in the selector expression of live method. If it matches, the event handler for the dynamic HTML will get execute else will not. [A good blog post on live method is here which you can refer for detailed understanding.]

 Because of this, the live had some issues on performance, jQuery chaining feature, etc. I will not discuss about the problems caused by live method in detail in this article. Instead there are some good write-ups and discussion about this in internet which can be referred.

In order to answer these issues, jQuery team added an alternate method called delegate which can be used in these scenarios.


Using delegate method in jQuery to bind events

Refer the below code,

    <script src="scripts/jquery-1.4.2.min.js" type="text/javascript"></script>   

    <script type="text/javascript">

        $(document).ready(function() {

            $("#clickMe").click(function() {             

                $("#dvDynamic").append("<a class=dynamiclink href=#>dynamic link</a><br>");

            });          

           

             $("#dvDynamic").delegate("a.dynamiclink", "click", function() {

                  alert("Clicked dynamic link");

               });  

 

        });

    </script>  

</head>

<body>

    <form id="form1" runat="server">

    <div>       

        <input type="button" id="clickMe" value="Click ME"/>

        <div id="dvDynamic">

         <b>Div Containing Dynamic Links: </b><br />

        </div>

   

    </div>

    </form>

</body>

</html>

 

Execute the page and see it in action. The live and delegate method has its corresponding die and undelegate method to unsubscribe the dynamic events attached to it.

 

Conclusion

This is yet another article which proves the power of jQuery library. The addition of these dynamic events method increased its flexibility to a new level.

Visit the official jQuery website to know more. Also, you can read the jQuery articles posted in codedigest to know more.

Happy Coding!!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments