0

i am building a web app. the main navigation of this web app is refreshed with jquery but after the refresh the jquery event doesnt work.

the "on button" has a jquery event bound to it with .on and everytime it is clicked it will append a paragraph. the "reset button" adds another "on button" but the jquery event doesn't apply to it.

i have used the .on method to circumvent that the second "on button" isn't in the DOM when the document is ready.

here is a simple example:

example on jsFiddle

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>blub</title>

<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function() {

        $(".reset").click(function() {
            $("nav").append('<button class="on">test</button>');
        })

        var count = 0;
        $(".on").on("click", function(){
            $(".cont").append("<p>Another paragraph! "+(++count)+"</p>");
        });

    });
</script>
</head>

<body>
    <button class="reset">reset</button>
    <nav>
        <button class="on">test</button>
    </nav>
    <div class="cont"></div>
<script>

</script>
</body>
</html>
arkhon
  • 765
  • 2
  • 11
  • 28

3 Answers3

2

The problem is hot you use method "on" try this:

<script type="text/javascript">
    $(document).ready(function() {

        $(".reset").click(function() {
            $("nav").append('<button class="on">test</button>');
        })

        var count = 0;
        $(document).on("click",".on", function(){
            $(".cont").append("<p>Another paragraph! "+(++count)+"</p>");
        });

    });
</script>

DEMO

Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
2

.on isn't a direct replacement for .live, its syntax is slightly different. If you want it to affect elements added to the DOM later, you need to use it like this:

$(document).on('click', '.on', function(){
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
0

You could also do it very simply this way -- this way the click handler gets assigned to each button as it is created.

$(document).ready(function() {

    var count = 0;

    $(".reset").click(function() {
        $("nav").append($('<button>', {
            class: 'on',
            html: 'test',
            click: function() {
                $('.cont').append('<p>Another paragraph! ' + (++count) + '</p>');
            }
        }));
    });
});
Monica Lent
  • 261
  • 1
  • 11