jQuery – Bind event to newly inserted element

If you have inserted DOM objects into the HTML in $(document).ready(function() {…}). Those binded events will not applied to newly inserted DOM objects. In the following example, a new button is inserted whenever the .btn is clicked. but it is only valid for the first .btn button.

<html>
  <head>
    <title>jQuery - Bind event to newly inserted element</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $('.btn').click(function() {
          $('<input class="btn" type="button" />').insertAfter(this);
        });
      });
    </script>
  </head>
  <body>
	  <input class="btn" type="button" />
  </body>
</html>

 

If you want to bind the event to all buttons including those which are newly inserted, the live() function could help. Try the following piece of code.

<html>
  <head>
    <title>jQuery - Bind event to newly inserted element</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $('.btn').live('click', function() {
          $('<input class="btn" type="button" />').insertAfter(this);
        });
      });
    </script>
  </head>
  <body>
	  <input class="btn" type="button" />
  </body>
</html>

 

Done =)

Reference: jQuery API – .live()

About these ads

5 thoughts on “jQuery – Bind event to newly inserted element”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s