0

I'm using jScroll (jscroll.com) in my Laravel 5.1 application for infinite scrolling. I'm further using some jquery which I want to be triggered on clicking the 'Like' button for each post. Jquery is working perfectly on the first page's posts i.e localhost/myproject/index but it is not triggered for the posts which are appended by jScroll from the next page(s) i.e localhost/myproject/index?page=2 etc.

Here is my code for displaying the posts:

    @foreach($posts as $post)
        <div class="panel panel-default">
            <div class="panel-body post">
                <h3>{{ $post->title }}</h3>
                <hr>
                <p>{{ $post->discripion }}</p>
            </div>
            <div class="panel-footer">
                <div class="btn-group">
                    <button type="button" data-id="{{$post->id}}" class="btn btn-default like-btn">Like</button>
                </div>
            </div>
    </div>
@endforeach

and the simple jquery that I want to be triggered for each posts is:

<script type="text/javascript">
            $('button.like-btn').on('click',function(){
                var post_id = $(this).data('id');
                alert('Liked post with id = ' + post_id);

            });
        </script>
Ahmed Raza
  • 294
  • 4
  • 18
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Alexander O'Mara Oct 17 '15 at 18:54

1 Answers1

1

It's because jquery doesn't bind to those elements (they are not in the DOM initially). Bind it to document instead, like this:

$(document).on("click", 'button.like-btn', function(event) { 
    alert("new link clicked!");
});

Look here for a little more

Community
  • 1
  • 1
Dennis
  • 909
  • 4
  • 13
  • 30