Peter
Peter

Reputation: 11835

Javascript - Onmiddleclick on a div


i need a non Jquery middleclick solution for all new browser. My idea was to use the onmiddleclick ... but this code does not work.

Hope someone can help.

HTML / JS Code

<div id="test" onmiddleclick="alert('middle');" ondblclick="alert('dbl');" > 
 CLICK HERE 
</div>

Example http://jsfiddle.net/392BK/

Thanks in advance!
Peter

Upvotes: 2

Views: 1192

Answers (5)

Town
Town

Reputation: 14906

Javascript:

<script type="text/javascript">
    function whichButton(e) {
        if (!e) var e = window.event;
        switch (e.which) {
            case 1: alert("Left"); break;
            case 2: alert("Middle"); break;
            case 3: alert("Right"); break;
        }
    }
</script>

HTML:

<div id="test" onmouseup="whichButton()">Click Me</div>

Have a read of this QuirksMode page for more information on event properties.

If possible, it's definitely worth using jQuery for things like this. Cross-browser compatibility for mouse-clicks is poor, and you'll need something more like this demo to provide support in all browers.

Upvotes: 4

Schovi
Schovi

Reputation: 1990

There is updated code from "Town" It will fix error in Firefox and prbably others browsers with "e is undefined" message.

In HTML you have to send event parameter like this:

<div id="test" onmouseup="whichButton(event)">Click Me</div>

Hope it will help you!

Upvotes: 1

netbrain
netbrain

Reputation: 9304

Here you go!

http://jsfiddle.net/392BK/1/

$().ready(function(){
    $("#test").mousedown(function(b){
      if(b.which==1)alert('Left Mouse Button Clicked');
      else if(b.which==2)alert('Middle Mouse Button Clicked');
      else if(b.which==3)alert('Right Mouse Button Clicked');
    });
})

EDIT:

My bad, but the event types still applies.

Upvotes: 0

Guffa
Guffa

Reputation: 700342

Use the onmousedown event. The event object has a button property which contains a bitmask for the buttons pressed. The value 4 means that only the middle button is pressed.

Upvotes: 0

niksvp
niksvp

Reputation: 5563

Using onclick and detecting clicks would be a good alternative.

Check this

Upvotes: 0

Related Questions