0

I created a very simple index.html file and inside I included some jquery script. You can see below:

    <script>
        $(document).ready(function(){
        var $tweets = $('.tweets');
        var current_position = -1;
        function getTweets(){
          var index = streams.home.length - 1;
          var cp = index;
          while(index >= current_position + 1){
            var tweet = streams.home[index];
            $tweets.append('<div class="twe"><span class="name" style="color:blue">' + '@' + tweet.user + ': ' + ' </span><span class="message">' + tweet.message + tweet.created_at + '</span></div>');
            index--;
          }
          current_position = cp;
        }
        getTweets();
        $('button').click(function(){
          getTweets();
        });
        $('.name').click(function(){
          $tweets.prepend('<div>' + 'objname' + streams.home.length + '</div>');          
        });

      });
</script>

there is one button used for updates all the tweets and dynamically put them in the section with class="tweets" part. And this button works fine no matter how many times I press it.

Then I add click event to all those with class name 'name' and once I click it , it will add 'objname' + streams.home.length to the front of my section class="tweets" part. The problem is first time , I CLICK the $('.name') it works fine , but later after I added more items through $('button') click event. it seems the new created $('.name') items is not clickable which means they don't generate 'objname' + streams.home.length to the front of my section with class="tweets" part. I am really confused here and don't know why.

  • 2
    Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – random_user_name Jan 13 '17 at 22:31

1 Answers1

0

try following

$("body").on("click",".name",function(){
          $tweets.prepend('<div>' + 'objname' + streams.home.length + '</div>');          
        });

As your element gets added runtime on the page, it needed to be taken care separately with help of "on" which bind events automatically when event gets created.

check reference

K D
  • 5,515
  • 1
  • 19
  • 32