Thanaporn
Thanaporn

Reputation: 189

How to show/hide comment using jquery while operate with DOM

I would like to thanks to this post enter link description here it is actually working but only when html document written directly. But it doesn't work while apply the same thing in document that created by jquery. can you please advise how to solve this?

my code is

<script>
var toggle = false;
$(function() {
    $('a.comments').click(function(e) {
        var $this = $(this);
        $('.toggleComments').toggle(1000,function() {
            if(!toggle) {
                $this.text('Hide Comments');
                toggle = !toggle;
            }else {
                $this.text('Show Comments');
                toggle = !toggle;
            }
        });
        e.preventDefault();
    });
}); 

var html;
$(document).ready(function()
{
html='<a href="#" class="comments">Show Comments</a><br /><div class="toggleComments">This is #comment1 <br />This is #comment2 <br /></div>';

$("#start").append(html);

}); 
</script>

</head>

<body>
<div id="start"></div>
</body>
</html>

Upvotes: 0

Views: 186

Answers (3)

Peter Olson
Peter Olson

Reputation: 142931

The problem is that you're trying to bind an event to an element before it exists. Just rearrange the code a little bit so the the element exists when you bind a click event to it. You can see it working on this jsFiddle page. You might want to rethink your logic a little bit since the text doesn't quite have the behavior you would expect.

var html;
$(document).ready(function() {
    html = '<a href="#" class="comments">Show Comments</a><br /><div class="toggleComments">This is #comment1 <br />This is #comment2 <br /></div>';

    $("#start").append(html);
    var toggle = false;
    $('a.comments').click(function(e) {
        var $this = $(this);
        $('.toggleComments').toggle(1000, function() {
            if (toggle) {
                $this.text('Hide Comments');
            } else {
                $this.text('Show Comments');
            }
            toggle = !toggle;
        });
        e.preventDefault();
    });
});

You can also use the on function to automatically bind to dynamically added elements. All you have to do is change $("a.comments").click(function() {}) to $(document).on('click', 'a.comments', function() {}).

Upvotes: 1

Rasmus
Rasmus

Reputation: 8486

Use .live to solve this something like this

$('a.comments').live('click',function(){
 //do your job here
});

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382160

To have your event handler applied to dynamically created elements, you need the on function :

 $(document).on('click', 'a.comments', function(e) {

The provided function will be called on click even on elements added to the DOM in the future.

Upvotes: 0

Related Questions