Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing textarea with ContentEditable attribute - Javascript runs multiple times

I'm working on a script to listen to the attribute contenteditable and simulate a changed handler. And the code runs multuple times. I'm not sure why that happens. Edit2: Updated the code that fixed the problem. The code looks like this:

    Event.observe(window, 'load', init, false);

    function init() {
        makeEditable('myeditablediv');
    }

    function makeEditable(id) {
        Event.observe(id, 'click', function(){test($p(id))}, false);
    }

    function test(obj) {
        var pre = obj.innerHTML;

        $(obj).one("focusout", function(){
            newcontent = obj.innerHTML
            alert(pre + ' ' + newcontent);
            if (newcontent !== pre) {alert('content is not the same')};         
        });
    }

This is originally a prototype script, that's why the $p because I had to change it's selector since I use jQuery as well.

In test() I output the previous value, then the new value. Then I try to compare these two. The next time I click the element myeditablediv, the previous variables are displayed, THEN the new ones. Third time I click, the first two, THEN the new third. Etc etc. I bet some of you have your facepalm ready right now, but I'm not good enough to spot this. Is it because of Event.observe? Edit: Edited the if statement.

like image 288
Kenny Bones Avatar asked Nov 26 '25 07:11

Kenny Bones


1 Answers

You can use .one() to attach the .focusout handler and have it run only once instead of adding more and more handlers each time.

So:

$(obj).one("focusout", function(){
    //....
});
like image 56
Matt Burland Avatar answered Nov 27 '25 21:11

Matt Burland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!