wong2
wong2

Reputation: 35710

how to fire the "ondblclick" event of a link

I want to do this: when you click a link on a page, it will open the link normally, but when you double click the link, it will alert the link's 'href' attribute.

However, when I try to double click a link, it will always open the link. Any idea?

Upvotes: 1

Views: 721

Answers (6)

NimChimpsky
NimChimpsky

Reputation: 47280

A double click is two clicks. Thus, it fires the click event.

Upvotes: 0

PleaseStand
PleaseStand

Reputation: 32052

The link opens after the first click of a double click, so you will need to add a time delay to determine which is which. Here's some code (using the jQuery JavaScript library for brevity) that works on all the browsers except Internet Explorer (try it out). If you can figure out why it doesn't, I'd like to know.

$('a').click(function(event) {
    var elem = $(this),
        clickTimeout = elem.data('clickTimeout');

    if(clickTimeout) {        
        // Double click; cancel the single click timeout
        clearTimeout(clickTimeout);
        elem.data('clickTimeout', null);

        alert(elem.attr('href'));

    } else {
        // Might be a single click; wait and see
        elem.data('clickTimeout', setTimeout(function() {
            // Single click; timeout was not cancelled
            elem.data('clickTimeout', null);

            // Navigate to the link's URL
            window.location.href = elem.attr('href');

        }, 500));
    }

    // Stops propagation and prevents default action
    return false;
});

Upvotes: 1

Barlow Tucker
Barlow Tucker

Reputation: 6519

This is tricky because the order of event is not the same in all browsers. Check out this article: http://unixpapa.com/js/mouse.html under the section for double clicks.

You could cancel the default action of clicking the link and write your own handler for the click event.

Upvotes: 0

Brad Mace
Brad Mace

Reputation: 27886

To avoid the link being opened, you may want to work with right-clicks instead.

Upvotes: 1

oezi
oezi

Reputation: 51797

maybe it's just a typo: the event you're looking for is named ondblclick, not ondbclick.

Upvotes: 1

Thariama
Thariama

Reputation: 50832

Because the onclick event gets fired before the ondbclick event. That is the reson why ondblclick does not get executed -> the link gets loaded first.

Upvotes: 0

Related Questions