Q:

Hide sub div on second time click

I've following script to show & hide subdiv on subsequent clicks but somehow it doesn't hide subdiv on second click.
Here's the code:
<script>
$.ajax({
   $('#floatcategory').append("<div class='floatbutton'
   id='float_"+categories[k][0]+"'>" +categories[k][1]+"</div>");
   $('#floatcategory').append("<div id='"+categories[k][0]+"_"+products[l][0]+"'>"
   +products[l][1]+"</div>");
});
 $('.floatbutton').live('click',function() {
    var floatidl=$(this).attr('id');
    var floatid=floatidl.substr(6);
    if ($('#'+floatidl'').hasClass("clicked-once")){
        $('[id^="'+floatid+'_"]').hide();
        $('#'+floatidl'').removeClass("clicked-once");
    }
    else {
        $('[id^="'+floatid+'_"]').show();
        $('#'+floatidl'').addClass("clicked-once");
    }
});
</script>

I'm using jQuery version 1.6. It doesn't hide the div. Can anyone help?

A:

Use .live() (for older jquery versions - < v1.7):
$('.floatbutton').live('click',function() {
    var floatidl=$(this).attr('id');
    var floatid=floatidl.substr(6);
    if ($('#'+floatid).hasClass("clicked-once")){
        $('[id^='+floatid+']').hide();
        $('#'+floatid).removeClass("clicked-once");
    }
    else {
        $('[id^='+floatid+']').show();
        $('#'+floatid).addClass("clicked-once");
    }   
});

or
$(document).delegate('.floatbutton','click',function() {
        var floatidl=$(this).attr('id');
        var floatid=floatidl.substr(6);
        if ($('#'+floatid).hasClass("clicked-once")){
            $('[id^='+floatid+']').hide();
            $('#'+floatid).removeClass("clicked-once");
        }
        else {
            $('[id^='+floatid+']').show();
            $('#'+floatid).addClass("clicked-once");
        }   
    });

Use .on() (for new jquery versions - >= 1.7):
$(document).on('click','.floatbutton',function() {
            var floatidl=$(this).attr('id');
            var floatid=floatidl.substr(6);
            if ($('#'+floatid).hasClass("clicked-once")){
                $('[id^='+floatid+']').hide();
                $('#'+floatid).removeClass("clicked-once");
            }
            else {
                $('[id^='+floatid+']').show();
                $('#'+floatid).addClass("clicked-once");
            }   
        });

Hope this helps you :)

