Search code examples
javascriptjqueryobjecteventsdom-events

Usage of the "mousedown" event in JavaScript and jQuery


What is the difference between jQuery mousedown method:

$(document).mousedown(callback);

and the usage of the mousedown event:

document.addEventListener('mousedown', callback, false);

Solution

  • $(document) is a jQuery object while document is a DOM object.

    jQuery allows you to interact with the document as a jQuery object using the $() syntax only after jQuery is loaded. If jQuery is not loaded there is no way to treat it as a jQuery object, as that type of object is not defined.

    There are a lot of things that you can do with document alone, HTML and javascript chief among them, but if you want jQuery functionality you have to include it.

    A fantastic document vs. $(document) primer can be found here.

    To answer the question in bold (how to achieve a jQuery $(document) object using pure JavaScript?):

    You would have to rewrite the jQuery functions in javascript. It's not worth the effort, but definitely possible.

    And, to address the edit:

    <script language="javascript">
        document.onmousedown = myMouseDownHandler;
    
        function myMouseDownHandler() {
          alert("A mouse down event took place within the document!");
        }
    </script>
    

    As @cookie_monster mentioned, if you want to use document.addEventListener() use mousedown instead of onMouseDown; without "on" and no special capitalization.

    jsFiddle