0

I have following problem. If I generate anhor "load_more_btn" via ajax then click function (the one with alert('test') ) wont work. Why is this happens and how to solve this problem?

<div id="content"></div>
<div id="load_more"></div>

        <script type="text/javascript">
        function getPhoto(paramType, param, page){
            $.ajax({
                url: "skrypt.php?paramType="+paramType+"&param="+param+"&page="+page
            }).done(function(data) {                            
                $('#content').html(data);
                var nextpage =page+1;
                $('#load_more').html('<a href="#" id="load_more_btn" data-paramType="'+paramType+'" data-param="'+param+'" data-page="'+nextpage+'"=>Wczytaj więcej</a>');
            });
        }

        $('#load_more_btn').click(function(){
                alert('test');
            });

    </script>

2 Answers2

2

Understanding Event Delegation

$(document).on("click","#load_more_btn",function(){
   alert('test');
});

If you are click to newly added item, nothing would happen. This is because of the directly bound event handler that we attached on load time. Direct events are only attached to elements at the time the .on() method is called. In this case, add more button did not exist when document is loaded.

Sadikhasan
  • 17,212
  • 19
  • 72
  • 111
0

This is because you assign the click handler before your content is loaded.

You should try using .on() instead:

$(document).on("click","#load_more_btn", function(){
                alert('test');
});

This assigns the handler to the document instead. And tries to find #load_more_btn onClick instead!

Philip G
  • 3,996
  • 2
  • 19
  • 40
  • @Styphon no it is not: http://api.jquery.com/on/ cite: "When a selector is provided, the event handler is referred to as delegated." – Philip G Feb 04 '15 at 12:47