kramer65
kramer65

Reputation: 53873

Javascript: How to hide a div which is dynamically created?

I'm creating a div dynamically using the following code:

$('#pageTabContent').append($('\
    <div class="tab-pane" id="'+user_id+'">\
        <div class="extras_area">\
            <div class="expand_heading">Header to be clicked</div>\
            <div class="expandable_content">this should be expanded.</div>\
        </div>\
    </div>'));

This is expanded within this HTML:

<div id="right_column">
    <ul id="pageTab" class="nav nav-tabs"></ul>
    <div id="pageTabContent" class="tab-content"></div>
</div>

I now want to expand the .expandable_content when I click the .expand_heading. To do this, I'm trying something like this in my javascript:

$("#right-column").on("load", ".expand_heading", hide);
$("#right-column").on("click", ".expand_heading", function(){
    $(this).next(".expandable_content").slideToggle(100);
});

Unfortunately, that doesn't work. I don't know how to hide the div correctly when it is dynamically created. Can anybody help me out here?

Upvotes: 2

Views: 1678

Answers (2)

Manolo
Manolo

Reputation: 26370

Why don't just use display:none rule:

$('#pageTabContent').append($('\
<div style="display:none;" class="tab-pane" id="'+user_id+'">\
    <div class="extras_area">\
        <div class="expand_heading">Header to be clicked</div>\
        <div class="expandable_content">this should be expanded.</div>\
    </div>\
</div>'));

Upvotes: 2

Sender
Sender

Reputation: 6858

Working Demo http://jsfiddle.net/t3WVs/

$('#pageTabContent').append($('\
    <div class="tab-pane" id="'+Math.random()+'">\
        <div class="extras_area">\
            <div class="expand_heading">Header to be clicked</div>\
            <div class="expandable_content">this should be expanded.</div>\
        </div>\
    </div>'));

//$(document).on("load", ".expand_heading", hide);
$(document).on("click", ".expand_heading", function(){
    $(this).next(".expandable_content").slideToggle(100);
});
// if needed default close expand
// $('.expand_heading').click();

Upvotes: 2

Related Questions