views:

64

answers:

2

How do you make javascript codes execute repeatedly? Say I have a DIV with id='box' and with innerHTML of 1. Then, say we have a link "add me up", which when you click and hold your mouse, the function will repeatedly increment the inner html by 1 until you let go of the mouse?

dragging mootools into the scenario, how can i run the code repeatedly in 2 second delay each?

A: 

[Edited]

var myTmr = null,
    incFunc = function () {
        if (!$('clickme').hasClass('down')) {
            return false;
        }

        var box = $('box');
        /* increment logic. */
        box.set('text', box.get('text').toInt() + 1);
        myTmr = incFunc.delay(2000);
    };

$('clickme').addEvents({
    'click': function (e) {
            e.stop();
        },
    'mousedown': function (e) {
            e.stop();
            this.addClass('down');
            incFunc();
        },
    'mouseup': function (e) {
            e.stop();
            this.removeClass('down');
            $clear(myTmr);
        }
});
sheeks06
`inc.Func()` should be `incFunc()`, no? And I think you don't need the `if (myTmr)`, because `$clear(myTmr)` alone will do the same.
Savageman
hi sheeks, i tried running you code with thise html code, but wouldnt wor, throws off a "too much recursion" error whether i hold or juct click the link. heres the html im playing with '<a href="#" id="clickme">addMeUp</a><div id="box">1</div>'
foxlance
Try my edited answer.
sheeks06
+1  A: 

here is not the ideal solution but the point to start from

var timer;
var up = function() {
    var box = $('box');
    var counter = box.get('text').toInt();

    counter++;
    box.set('text', counter);
};
$$('a#addMeUp').addEvents({
    'mousedown': function(event) {
        event.preventDefault();

        timer = up.periodical(2000);
    },

    'mouseup': function() {
        $clear(timer);
    }
})
Tror
timer is not assigned. to any. must be, timer = up.periodical(2000);
sheeks06
thanks ;). updated
Tror
Hi tror, i couldnt seem to make your code work, i get no error, just nothing, cant really do much or offer any explanation as im a total noob at javascript. heres the html im playing with "<a href="#" id="addMeUp">addMeUp</a><div id="box">1</div>"
foxlance
I used your markup and it works just fine for me in all browsers.
Tror
Hi Tror, i got your code working now. Works on Chrome, Safari and IE, but not Firefox. I was able to edit it a bit to work with 1.1 but for OE, I have to comment out the line 'event.preventDefault();' . Still, even for 1.1, Firefox doesn't cooperate :( My firebug console doesn't throw any error.
foxlance
sorry, works for firefox 3.6.6, but my version, 3.6.10 is not working, grrrr!
foxlance
just checked in 3.6.10. It works. See [screenshot](http://clip2net.com/s/ygOd)
Tror