0

Im making a sort of like social network website like twitter. When the user wants to edit a post I open a div append a textarea, a "save" button and a "cancel" button with jquery.

But the cancel button only works once, the 2nd time the user clicks for editing a post, the cancel button doesn't work anymore.

$(function() 
{    
    function edit(chirp_id)
    {
        var div1 = $('<div></div>');
        div1.addClass('thumb2');
        div1.attr('id', chirp_id);
        $(div1).css('display','none');

        if($(div1).is(':visible'))
        {
            return;
        } 
        else
        {
            // Before the 'cancel' button I append the textarea and 'save' button

            var cancel = $('<button></button>');
            cancel.attr("id","cancelEdit");
            cancel.text("Cancel");

            cancel.addClass('button');
            cancel.appendTo(div2);

            $('#cancelEdit').click(function()
            {
                $(div1).fadeOut("slow");
            });
        }

        my_edit = edit;
     });

I call my function with javascript

function edit_chirp(chirp_id)
{
    my_edit(chirp_id);
}
1
  • Its just another div that contains the textarea and the 2 buttons. div2 and appended to div1 Commented Oct 15, 2013 at 12:23

3 Answers 3

1

Try this .. bind event with dom not with ID ..

$(function () {

function edit(chirp_id) {
    var div1 = $('<div></div>');
    div1.addClass('thumb2');
    div1.attr('id', chirp_id);
    $(div1).css('display', 'none');

    if ($(div1).is(':visible')) {
        return;
    } else {
        //Before the 'cancel' button I append the textarea and the 'save' button
        var cancel = $('<button></button>');
        cancel.attr("id", "cancelEdit");
        cancel.text("Cancel");

        cancel.addClass('button');
        cancel.appendTo(div2);

        cancel.click(function () {
            $(div1).fadeOut("slow");
        });
    }
    my_edit = edit;

});
Sign up to request clarification or add additional context in comments.

Comments

1

Better use delegates using .on event handler because your div1 is created dynamically

$(document).on('click', '#cancelEdit', function () {
                $(div1).fadeOut("slow");
            });

Missing to close edit function

2 Comments

And also look for a missing bracket closing your function on the first block posted.
I have tried using the delegates...it still only works once. The 2nd time the cancel button doesn't work anymore
0

probably to do with closure. try:

cancel.click(function (event) {
    $(event.target).closest(".thumb2").fadeOut("slow");
});

1 Comment

I don't understand what can be causing this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.