Tim
Tim

Reputation: 741

Limiting click detection on the page [javascript]

I'm trying to limit the user's ability to click on an object to a certain time limit. I looked around and found that apparently, setTimeout() is the correct function to use for this type of thing. I've applied the function to my code, but its not working. I'm thinking/know now that the problem is that the setTimeout in my code isn't limiting the actual click event, which I need to do. Here is a snippet of my click code:

function clickRun(event) {
    var $objectVersion = correspondingObject(event.target.id);
    if (isAnyVisible() == false) { // none open
        $objectVersion.makeVisible();
    } else if (isAnyVisible() && $objectVersion.isVisible()) { //click already open div
        $objectVersion.makeInvisible();
    } else if (isAnyVisible() && $objectVersion.isVisible()==false) { //different div open
        searchAndDestroy();
        $objectVersion.delay(600).makeVisible();
    };
 };

$('.ChartLink').click(function(event) {
    setTimeout(clickRun(event),5000);
});

I've also created a JSFiddle to represent what I'm talking about: http://jsfiddle.net/FHC7s/

Is there a way to achieve limiting the actual click detection on the page?

Upvotes: 0

Views: 210

Answers (3)

Lawrence Jones
Lawrence Jones

Reputation: 955

Have a look at this JSFiddle, I've set it up so you can have the button disable itself for time duration after detecting a click. Just make sure to remember how your closures are operating with your setTimeouts.

Upvotes: 1

Hylianpuffball
Hylianpuffball

Reputation: 1561

Your code contains an error... your line should be

setTimeout(function(){clickRun(event)},5000);

but even then I don't think that's exactly what you're looking for; that code will "delay" the click by 5 seconds, not actually prevent more clicks. If your true intent is to ignore all clicks after a certain amount of time, then I would go with mowwalker's answer; there's no way to stop the clicks, but you can check to see if you should honor them or not.

Upvotes: 0

mowwwalker
mowwwalker

Reputation: 17334

I think the easiest way to do it is to keep track of the time of the previous click and if the current click is too soon after that, then don't do anything:

onClick = function(){
    if(new Date().getTime() - lastCheck < MIN_CLICK_SPACING) return;
}

Upvotes: 2

Related Questions