8

Hi I want to have a dblclick() on the right click as the google maps have to zoom in and zoom out. Is there any way to do that. I have written the dblclick but now its working with only left click. Any pointers on how to do this. Here is my code

         $("div#demo1").dblclick(function(e) {
            //alert(e.getElementById());

            if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
                alert("Left Mouse Button was clicked on demo1 div!");
                $("div.window").animate({
                'height':'+=20', 'width':'+=20'
                },0,function(){
                    jsPlumb.repaintEverything();
                    jsPlumb.repaintEverything();
                });
                // Left mouse button was clicked (all browsers)
            }
            else if( (!$.browser.msie && e.button == 2) || ($.browser.msie && e.button == 3) ) {
                alert("right click double");
            }
        }); 
2
  • 3
    jQuery normalizes the button value to e.which, you don't need the plumbing code. Commented Aug 23, 2012 at 19:10
  • @Esailija: yeah I saw that now. Is there a way to call on double click and not on single click? Commented Aug 23, 2012 at 19:17

5 Answers 5

11

There is another way you could detect a double right-click that does not involve fiddling with timers or keeping track of click counts manually. Using the .detail property of the event object in a mouseup or mousedown event. .detail holds the click count which will tell you how many clicks have happened recently. If .detail === 2 it was a double-click.

// suppress the right-click menu
$('#target').on('contextmenu', function (evt) {
    evt.preventDefault();
});

$('#target').mouseup(function (evt) {
  if (evt.which === 3) { // right-click
    /* if you wanted to be less strict about what
       counts as a double click you could use
       evt.originalEvent.detail > 1 instead */
    if (evt.originalEvent.detail === 2) { 
      $(this).text('Double right-click');
    } else if (evt.originalEvent.detail === 1) { 
      $(this).text('Single right-click');
    }
  }
});

You might notice that I am using evt.originalEvent.detail to access the property instead of just .detail. This is because jQuery provides it's own version of the event object which does not include .detail, but you can access the original event object that the browser returned via .originalEvent. If you were using pure JavaScript instead of jQuery you would just use evt.detail.

Here's a working example.

Sign up to request clarification or add additional context in comments.

1 Comment

This answer is far superior to the rest for one simple reason: the end-user gets to decide what counts as a double-click. If you hard-code the default timing into your code, people who've changed their double-click timing from the default might 1) think your site is broken, and/or 2) not use it because they can't.click fast enough. I just tested this with different click speed settings on Windows in Chrome, Firefox, Opera, and IE, and it worked perfectly in all of them.
6

There is no real way to do it, you can emulate it by taking the default timer for double clicks which IIRC is 300ms:

function makeDoubleRightClickHandler( handler ) {
    var timeout = 0, clicked = false;
    return function(e) {

        e.preventDefault();

        if( clicked ) {
            clearTimeout(timeout);
            clicked = false;
            return handler.apply( this, arguments );
        }
        else {
            clicked = true;
            timeout = setTimeout( function() {
                clicked = false;
            }, 300 );
        }
    };
}

$(document).contextmenu( makeDoubleRightClickHandler( function(e) {
    console.log("double right click" );
}));

http://jsfiddle.net/5kvFG/2/

1 Comment

Hard coding the timing doesn't account for users who change their double-click speed, which Useless Code's answer does.
1

Because the right-click has meaning to the user agent that is outside the purview of javascript (the context menu), you're going to have to do some dancing around.

First, you should disable the context menu on the target element:

document.getElementById('demo1').oncontextmenu = function() {
    return false;
};

Now, when we right click, there won't be the context menu messing up the second click.

Next, understand that "double-click right" does not, generally speaking, exist. Even though you can bind the dblclick event, that isn't a generic event. "Double-click" is, by definition, double-clicking with the left mouse button.

So, we'll have to use the mousedown event, check to see how many times the right has been clicked, and react after two. I created a small helper function that keeps track of the click count and resets the state after a short time-frame.

var RightClick = {
    'sensitivity':350,
    'count':0,
    'timer':false,
    'active':function () {
        this.count++;
        this.timer = setTimeout(
            this.endCountdown.bind(this),
            this.sensitivity
        );
    },
    'endCountdown': function () {
        this.count = 0;
        this.timer = false;
    }
};
$("div#demo1").mousedown(function(e) {
    if(e.which == 3) {
        RightClick.active();
        if (RightClick.count == 2)
            alert("right click double");
    }
});

Try it here: http://jsfiddle.net/94L7z/

You can adjust the sensitivity rate, allowing for shorter or longer double-clicks, depending on your preference.

Documentation

6 Comments

Hard coding the timing doesn't account for users who change their double-click speed, which Useless Code's answer does.
@kevinmicke The client tracks the click count and resets it after a certain time, about 350ms. I don't disagree with using event.detail... I just didn't know about it. I was, clearly, not alone in this. That said, this type of solution works just as well. You can do a slow double-click on the other method's example and it only registers a single click too.... and in that way, this approach may even be superior. What if your users are complaining that the double-right-click isn't working reliably, you determine it's because of speed. This you can adjust. Event.detail, cannot adjust.
I didn't know about event.detail either until I saw the other answer. I would disagree that this type of solution works just as well though: changing your system's double click speed is really the only way to test what I mean. Some users change their double click speed to be really slow because they have trouble using a mouse/touchpad/etc., so for those users a double click might be two clicks within a full second on any other site or program they use. But when they come to a site that hard codes a double-right-click as being 350 ms, they'll probably think the site is broken.
@kevinmicke So we have a circumstance where edge cases (users who have changed their double-click speed at the OS level) may create an issue. I guess I'd still rather maintain control over it, unless it was becoming an issue. Maybe a combination of both solutions is better? At any rate, the techniques are on the table for future readers to decide what is best for their use-case.
@kevinmicke Also, the downvote? "This answer is not useful"-- I disagree there too. Not that I'm too worried about the points, but I am also confident that this answer, or Esailija's, are not useless. It's weird to me that you've crusaded against our approach so vehemently.
|
0

The problem is the concept of double clicking is only relevant to the left mouse button as far as JS is concerned. So no matter how many time, and how fast you click the right mouse button, it just registers as a bunch of single clicks. So what to do?

  1. Create a global variable to track click count
  2. detect a single right-click, you already know how to do this it seems
  3. set the global variable that the right-click was fired once
  4. set a timeout, so if another right click doesn't come through in a reasonable time to be considered a dblclick the global variable resets to 0. I recommend 300 ms, it seems to be the most natural
  5. each time a right-click registers check that variable, if it's more than one, fire your double-right-click handler.
  6. you may want to make that global variable an object so you can track which element registered the right click and expire specific element right clicks accordingly. This will allow you to ignore if they double click while moving the mouse over various objects. I consider this optional as the chain of events are unlikely for a user to follow, but depending on your app may result in unexpected functionality.

Comments

0

It might be better to define a jQuery function with this (try it):

var precision = 400;
var lastClickTime = 0;

$(document).ready(function()
{
    var div = $('#div');

    $(div).bind("contextmenu", function(e)
    {
        return false;
    }); 

    $(div).mousedown(function(event)
    {
        if (event.which == 3)
        {
            var time = new Date().getTime();

            if(time - lastClickTime <= precision)
            {
                // DOUBLE RIGHT CLICK
                alert('double click');
            }

            lastClickTime = time;
        }
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.