Wednesday, September 30, 2009

[jQuery] Re: Binding a unique single and double click command

in the double click function you'd have to clearTimeout on the first
function otherwise it will run anyways.

readysalted wrote:
> I'd use this approach -
>
> var clicks = 0;
>
> $('.todo_item h2').live('click', function() {
> // count the click
> click++;
>
> // only set the timeout if the first click to prevent multiple
> firing
> if( click == 1) setTimeout( "doTheAction()", 300);
> });
>
> function doTheAction()
> {
> if(click == 1) editInPlace();
> if(click == 2) showExtra();
>
> // reset click
> click = 0;
> }
>
> so you will only do something after the timeout fires, and you count
> the clicks. If the user clicks a 2nd time before the timeout fires
> you'll get the 2nd action. If not, you get the first.
>
> NB: not tested, just an idea. Test it hard to make sure you don't
> create lots of timeouts and crash the browser :)
>
>
> On Sep 29, 3:41 pm, Sam <samueljhart...@gmail.com> wrote:
>
>> I'm trying to write some jQuery to do the following:
>>
>> If a user clicks once on an object, do X.
>>
>> If a user clicks twice on an object, do Y, but not X.
>>
>> I've been having some trouble with this as, obviously, a double-click
>> will trigger the single-click twice. Here is a failed attempt:
>>
>> $('.todo_item h2').live('click', function() {
>> var startTime = new Date();
>> $(this).mousedown(function() {
>> var endTime = new Date();
>> if (Math.abs(endTime - startTime) < 300) { editInPlace }
>> else { showExtra }
>> });
>>
>> });
>>
>> where editInPlace and showExtra are some functions I have defined
>> elsewhere in the document. This method, however, relies on a second
>> click, or mousedown at least, to work, which fails if the user only
>> clicks once.
>>
>> I have also looked into setTimeout but without any fruitful results.
>> Anyone have any suggestions on how to code thsi?
>>

No comments: