mozilla
Your Search Results

    GlobalEventHandlers.onclick

     

    The onclick property returns the click event handler code on the current element.

    Note: When using the click event to trigger an action, also consider adding this same action to the keydown event, to allow the use of that same action by people who don't use a mouse or a touch screen.

    Syntax

    element.onclick = functionRef;
    

    where functionRef is a function - often a name of a function declared elsewhere or a function expression. See "JavaScript Guide:Functions" for details.

    The event object passed to the specified event handler function is a MouseEvent.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>onclick event example</title>
    <script>
    function initElement() {
      var p = document.getElementById("foo");
      // NOTE: showAlert(); or showAlert(param); will NOT work here.
      // Must be a reference to a function name, not a function call.
      p.onclick = showAlert;
    };
    
    function showAlert() {
      alert("onclick Event detected!")
    }
    </script>
    <style>
    #foo {
      border: solid blue 2px;
    }
    </style>
    </head>
    <body onload="initElement()";>
    <span id="foo">My Event Element</span>
    <p>click on the above element.</p>
    </body>
    </html>
    

    Or you can use an anonymous function, like this:

    p.onclick = function() { alert("moot!"); };
    

    Notes

    The click event is raised when the user clicks on an element. The click event will occur after the mousedown and mouseup events.

    Only one click handler can be assigned to an object at a time with this property. You may be inclined to use the EventTarget.addEventListener() method instead, since it is more flexible and part of the DOM Events specification.

    Specification

    Defined in HTML5. FIXME:

    Document Tags and Contributors

    Last updated by: teoli,
    Hide Sidebar