Replacing textarea with ContentEditable attribute - Javascript runs multiple times

I am working on a script to listen for an attribute contenteditable

and simulate a modified handler. And the code works over and over again. I don't know why this is happening. Edit2: Updated code that fixed the issue. 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, so $p

because I had to change its selector since I am also using jQuery.

We test()

display the previous value, and then the new value. Then I try to compare the two. The next time I click an item myeditablediv

, the previous variables will be displayed, then the new ones. The third time I press, the first two, then a new third. Etc etc. I bet some of you have your facepalm ready right now, but I'm not good enough to notice. Is it because of Event.observe

? Edit: edited if statement.

+3


source to share


1 answer


You can use . one () to attach a handler .focusout

and run it only once instead of adding more handlers time.

So:



$(obj).one("focusout", function(){
    //....
});

      

+2


source







All Articles