0

a question, I use jquery to automatically reload every 5 seconces a remote php page. No problem. This page contains assets (clickable), and I can not make it work. the element appears inactive. I said that I want to use for another jquery fontion.

Index.html :

<html>
    <head>
        <meta charset="utf-8" />
        <title>CPAC</title>
    </head>
    <body>
<a title="" style="padding : 1px 2px;" href="#"  class="cl"><img src="images/fastcoin.png"></a>
        <div id="lWorkers">Loading ...</div>
        <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
         <script type="text/javascript">
            $(document).ready(function(){
                    var interval = 5000;   
                    var refresh = function() {
                        $.ajax({
                            url: "lWorkers.php",
                            cache: false,
                            success: function(data) {
                                $( "div#lWorkers" ).html(data);
                                setTimeout(function() {
                                    refresh();
                                }, interval);
                            }
                        });
                    };

                    refresh();          

                    $(".cl").click(function() {
                    alert( "toto" );
                    return false;
                    });
            });
        </script>
    </body>
</html>

And lWorkers.php sample return :

<a title="" style="padding : 1px 2px;" href="#"  class="cl"><img src="images/fastcoin.png"></a>
<a title="" style="padding : 1px 2px;" href="#"  class="cl"><img src="images/fastcoin.png"></a>
<a title="" style="padding : 1px 2px;" href="#"  class="cl"><img src="images/fastcoin.png"></a>
<a title="" style="padding : 1px 2px;" href="#"  class="cl"><img src="images/fastcoin.png"></a>
Giveme
  • 23
  • 5

3 Answers3

1

The .c1s that you're adding via ajax don't exist yet when you bind the click handlers. You do the binding as soon as the document is ready but those elements are loaded later. Best bet is to use event bubbling. Jquery makes it easy with its on() method.

$( "div#lWorkers" ).on('click', 'a', function() {
    alert('toto');
});

The other option is to do the click binding in the success() callback of your refresh function, after you've appended the HTML to the DOM.

Community
  • 1
  • 1
Will
  • 4,075
  • 1
  • 17
  • 28
0

Change:

$(".cl").click(function() {
                alert( "toto" );
                return false;
                });

To:

$("body").on("click", ".cl", function() {
                alert( "toto" );
                return false;
                });

.click doesn't work after Ajax content refresh. "On" does.

0

Use jQuery's .on() function...

Chicharito
  • 1,450
  • 8
  • 31
  • 49