serdar
serdar

Reputation: 454

jquery add new div onclick

I have a list of div

<li class="comment">
     <div class="comment-body" id="comment-body">
            <div class="comment-author vcard">
                <div class="lightbox-photo">
                    <a class="image-overlay" href='<%# "Foto/profil/foto_buyuk/" + Eval("Yorum_Profil_Foto_Buyuk") %>' data-rel="prettyPhoto" title='<%# Eval("Yorum_UserName")%>'><img src='<%# "Foto/profil/foto_kucuk/" + Eval("Yorum_Profil_Foto_Kucuk") %>' alt='<%# Eval("Yorum_UserName")%>' class="avatar" />
                    </a>
                 </div>
                 <cite class="fn"><asp:HyperLink ID="linkProfil" runat="server" Text='<%# Eval("Yorum_UserName")%>' NavigateUrl='<%# "~/profil.aspx?user_id="+Eval("User_ID") %>'></asp:HyperLink></cite>
                 <cite class="fn-time"></cite> 
               </div>
        <p><%# Eval("Yorum_Text")%></p>
           </div>
         </div>
     </div>
</li>

I want to add a new div on div click. I wrote jquery codes but it doesnt work.

function addcommentdiv () {
    var NewContent = '<div class=""><input name="name" type="text" id="name" size="20" value="" style="height:20px; margin-top:10px; width:480px;margin-left:90px; font-size:14px;" /></div>'
    $('.comment-body').click(function () {

        var index2 = $('.comment-body').index(this);
        if (NewContent != '') {
            $('.comment-body').eq(index2).after(NewContent);
            NewContent = '';

        }
        else {
            $('.comment-body').eq(index2).next().toggle();

        }

    });

};

Why it doesn't work or how can I add a new div to clicked div below (as twitter reply)? Before I wrote some code. It was working but there was a problem: it was working for one div only.

Upvotes: 0

Views: 14104

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

Try

function addcommentdiv () {
    var NewContent = '<div class="reply"><input name="name" type="text" id="name" size="20" value="" style="height:20px; margin-top:10px; width:480px;margin-left:90px; font-size:14px;" /></div>'
    $('.comment-body').click(function () {
        var $this = $(this), $reply = $this.next('.reply');

        if ($reply.length) {
            $reply.toggle();
        } else {
            $(NewContent).insertAfter($this);
        }
    });
};

Demo: Fiddle

Upvotes: 3

user856358
user856358

Reputation: 593

I'm not too familiar with jquery, but you can add a new div through javascript

var NewContent = '<div class=""><input name="name" type="text" id="name" size="20"          value="" style="height:20px; margin-top:10px; width:480px;margin-left:90px; font-  size:14px;" /></div>'


$('.comment-body').click(function () {
var newdiv=document.creatElement(NewContent);
var toattach= document.getElementById('comment-body');
toattach.appendchild(newdiv) ;
}
else {
    $('.comment-body').eq(index2).next().toggle();

}

});

Upvotes: 0

Related Questions