Search code examples
ajaxmootools

Edit button with comments using MooTools/AJAX


So I'm using a PHP API to interact with, to build a forum using MooTools. I can get comments from my database and add comments, but I want to inject an edit button to coincide with each comment.

I inject the comments using:

function domReady() {
    $('newComment').addEvent('submit', addComment);
}

function addComment(e){
e.stop();
var req = new Request({
    url:'control.php?action=insertPost',
    onSuccess:addajaxSuccess
}).post(this);
}


function addajaxSuccess(idNo) {
new Element('span',{
    'text':'Post successful.'
}).inject($(newComment));
$('commentList').empty();
domReady();
}

I want to attach an edit button to each comment injected, and add an event listener on the button to change the comment into a textarea for editting, with an update button.

Any ideas?


Solution

  • If you want to bind a global events to a dynamic content you have better look into Element Delegation In mootools.

    Basically it's give you the ability to bind event to some container and "listen" to events of that children container base on selectors. I made you a little example here:

    http://jsfiddle.net/xwpmv/

    mainContainer.addEvents({
        'click:relay(.mt-btn)': function (event, target) {
            var btn = target;
            if(btn.get('value') == 'Edit'){
                btn.set('value','Done Editing');
                var content = btn.getPrevious();
                content.setStyle('display','none');
    
                var textarea = new Element('textarea').set('text',content.get('text'));
                textarea.inject(btn,'before');
    
            }
            else{
                 btn.set('value','Edit');    
                 var textarea = btn.getPrevious();
                var new_value = textarea.get('value');
                textarea.destroy();
                var content = btn.getPrevious();
                content.set('text',new_value);
                content.setStyle('display','block');
            }
        }
    });
    

    Here you can see the mainContainer listen to the click event of every element who has mt-btn class (the buttons)

    • You have several errors in your code but maybe it is just an example so I didn't relate to it.