views:

143

answers:

2

Hi, I want to disable mouse left click. I use the following script but not work.

<h:form>
        <a4j:commandButton value="TestButton" onclick="alert('button cliked')"/>
</h:form>

JavaScript is :

<script type="text/javascript">
        document.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP | Event.CLICK);
        document.onmousedown = clickIE4;
        document.onmouseup = clickIE4;
        document.onclick = clickIE4;

        function clickIE4()
        {
            return false; 
        }
</script>

Help me. Thanks for your effort.

+6  A: 

You are going about this incorrectly. You want to disable the button (enabled=false), not capture mouse clicks.

Yann Ramin
+2  A: 

When using that style of handler, return false from the handler code:

<a4j:commandButton value="TestButton" onclick="alert('button clicked'); return false;"/>

As theatrus said, though, if your goal is to disable the button, you're better off actually disabling the button rather than preventing clicks on it. But in terms of your question "how do I disable a left click," that's the answer.

More thoroughly, there are two different ways to attach event handlers:

DOM0 (the style you've used): Return false from the handler code to stop the event (prevent it bubbling up to other elements) and prevent the default action:

<someElement onclick="return false;">

DOM2 (with JavaScript code): DOM2 handlers are attached via addEventListener (or attachEvent, on IE). Here's an example, assuming an element with the id "foo":

// Attaching:
var elm = document.getElementById("foo");
if (elm.attachEvent) {
    elm.attachEvent("onclick", handler);
}
else if (elm.addEventListener) {
    elm.addEventListener("click", handler, false);
}

// Handler:
function handler(event) {
    // DOM standard is that `event` is an argument to the
    // handler; IE uses a global event object instead.
    // This line handles that.
    event = event || window.event;

    // Cancelling bubbling:
    if (event.stopPropagation) {
        // DOM standard
        event.stopPropagation();
    }
    else {
        // Older mechanism
        event.cancelBubble = true;
    }

    // Preventing default action:
    if (event.preventDefault) {
        // DOM standard
        event.preventDefault();
    }
    else {
        // Older mechanism
        event.returnValue = false;
    }
}

Some reference material:

T.J. Crowder