开发者

Javascript - Onmiddleclick on a div

开发者_StackOverflow

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


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.


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!


Using onclick and detecting clicks would be a good alternative.

Check this


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜