Keyboard and Mouse Events in jQuery with methods and properties


Published on 09 March 2023


Keyboard and Mouse Events in jQuery with methods and properties

How jQuery events work

Events play a critical role in the way websites are developed. Most web applications use events to react to user input, communicate with web servers and maintain a consistent user interface. jQuery is a popular JavaScript library used for registering and triggering events. It also provides default event handlers to respond to common event types. This makes it much easier to create functional web applications.

A computerized event-based system responds to different inputs and generates output based on predetermined rules. It usually communicates with other system components and performs tasks at specific times or intervals.

For example, the system that runs your car normally runs its engine at a consistent speed and timing. However, when you press the gas pedal, the car's engine speed increases. This is an example of an event triggering a handler; it determines how your car responds to your actions.

Events are triggered by different external influences such as network communications or programmatic user actions. These triggers initiate scripts that perform tasks based on predetermined rules.

For example, when a user clicks on a menu item, an event handler in the menu's code responds by displaying a different menu item.

An event can also notify you of errors or other unexpected behavior when initiating code execution in response. This allows you to swiftly identify and correct any issues before they negatively impact your application's performance or functionality.

Since events are initiated by external forces, they're always contextual and variable based on the situation. For this reason, jQuery provides various default event handlers for common scenarios such as mouse clicks and keyboard inputs. You can also write your own custom event handlers as needed for your application's unique needs. Using this approach, you can easily create interactive web pages that respond seamlessly to various user inputs. This reduces user interfaces from clunky popups or menus with dozens of options to only those relevant to the current situation.

Developers often use events for implementing quick responses and enhancing page load speeds. Many users click on links in web pages without meaning to do so- which initiates an event handler in the browser window code. This causes the URL of the linked website to open in a new tab or window instead of the current one. Additionally, registering event handlers ahead of time saves time when performing repetitive tasks such as form validation or AJAX callbacks. This makes development much faster without reducing quality due to fatigue from manually performing slow loops over and over again with callback functions.

Events are an easy way to implement interactive web pages without writing complex code or customizing browser settings each time something interesting occurs on a webpage. They allow you to easily register and trigger various events without worrying about how they affect the currently open webpage window. Additionally, using events helps enhance page load times by automating repetitive tasks such as form validation and loading external JavaScript files into the page window itself.

Explicit operation of an event in jQuery

The events propagate from the element where they have been produced, for example a mouse click, up the html DOM until they find, in case there is one, a handler.
If they meet that handler, they execute it and follow their way up until they reach the top of the DOM.
Step by step what happens is (in a simplified way):

  1. We click on a li. As it has a handler it is executed.
  2. The event propagates to the ul, not having a handler the event continues upwards.
  3. The event arrives to the body that has a handler for the click event. This is executed.
  4. The event continues upwards but does not find any handler again.

Event capture

We have two possibilities to capture and react to events:

  1. Using general functions.
  2. Using specific functions for each event that have the event's own name.

General functions for capturing events

There are mainly two, the functions .on() and .one(). Both are analogous functions and the difference is that .one() executes the handler at most once and then deactivates it.
In both I indicate the name of the event that I want to capture and I can have a direct association of the handler to the event or a delegated association.

  • .on()
    Example:
    In the following example we have the option to introduce two different numbers and to make operations of addition, subtraction, multiplication and division.
    Try it Yourself
  • .one()
    Example. Difference between the one() and on() methods:
    Try it Yourself

Event's own name

The operation is analogous to the capture with .on() or .one() but the "important" events have their own dedicated functions. This type of capture does NOT allow me to DELEGATE ASSOCIATION.
Among the most prominent named events:

  • .change()
  • .hover()
  • .mouseenter()
  • .resize()
  • .click()
  • .keypress()
  • .mouseleave()
  • .scroll()
  • .dblclick()
  • .keydown()
  • .mousemove()
  • .select()
  • .focus()
  • .keyup()
  • .mouseout()
  • .submit()
  • .focusout()
  • .mousedown()
  • .mouseover()

The Event object. Event properties

The event object has many properties and methods. The most commonly used are the following, where e is the event:

  • e.currentTarget
    It works in the same way as this inside a function.
    Try it Yourself
  • e.stopPropagation
    Stops the propagation of an event to higher elements.
    Try it Yourself
  • e.stopImmediatePropagation
    Stops the upward propagation of the selected element and the rest of the handlers.
    Try it Yourself
  • e.delegatedTarget
    It is applied as an event property on the main element that is selected.
    Try it Yourself
  • e.Target
    It is applied to events and returns the DOM element that was triggered by the event along with its possible properties.
    Try it Yourself
  • e.pageX
    Position of the mouse with respect to the left of the document.
    Try it Yourself
  • e.timeStamp
    This event property calculates the difference in milliseconds between the time the event was created and January 1, 1970.
    Try it Yourself
  • e.metaKey
    It is true if we have pressed the Windows key in Windows and the command key in Mac.
    Try it Yourself
  • e.pageY
    Position of the mouse with respect to the upper zone of the document.
    Try it Yourself
  • e.type
    Name of the event that has occurred. Especially useful if our handler is for more than one event and we want to do different things.
    Try it Yourself
  • e.preventDefault
    Prevents the default behavior of the selected element.
    Try it Yourself
  • e.which
    Contains the code of the key or mouse button (1-left, 2-center, 3-right).
    Try it Yourself

Classification of events according to their function

The above-mentioned events can also be classified according to operation:

  • Keyboard events
  • Mouse Events

Keyboard events

There are mainly three of them:

  • keydown()
    Event that is fired when I press a key while inside an element. It includes "special keys" and is Case Insensitive.
    Try it Yourself
  • keyup()
    Event that is fired when I release the pressed key.
    Try it Yourself
  • keypress()
    Event that fires when I press a key while inside an element. It does not include special keys and is Case sensitive.
    Try it Yourself

Mouse Events

  • mousedown()
    When the mouse is pressed while inside an element.
    Try it Yourself
  • mouseup()
    When I release the mouse after clicking on one of its buttons.
    Try it Yourself
  • mouseenter()
    When the mouse enters an element. Refers only to the element.
    Try it Yourself
  • mouseleave()
    When the mouse leaves an element. Refers only to the element.
    Try it Yourself
  • mousemove()
    When I move the mouse inside an element.
    Try it Yourself
  • mouseover()
    When the mouse enters an element. Refers to the element and its children.
    Try it Yourself
  • mouseout()
    When the mouse leaves an element. Refers to the element and its children.
    Try it Yourself
  • click()
    When I do single mouse click inside an element.
    Try it Yourself
  • dblclick()
    When I double-click the mouse inside an element.
    Try it Yourself

Connecting and disconnecting Handlers

The connection of handlers to elements we had already seen at the beginning of the article using methods like .on() and the event named methods like $().click().

To disconnect those Handler jQuery mainly provides us with the .off() function that can be used in several ways and does the opposite effect of .on(). It can be used in several ways and some of the most common ones we will illustrate below:

$("some_selector").off("event1 event2...eventN");
Try it Yourself

Simulating events artificially. To create my own events

Sometimes it may be necessary to simulate the occurrence of an event by artificially triggering it when I am interested.
This is achieved with the following functions:

  • trigger()
    The default behavior is still maintained and there is propagation.
    Try it Yourself
  • triggerHandler()
    The default behavior of the element is not executed, I must have an associated handler for the concrete event and there is no propagation of the event.
    Try it Yourself

To create my own events I will use the functions .on() and .trigger() and .triggerHandler().

$("selector").on("my_event"..........);
$("........").trigger("my_event");
$("........").triggerHandler("my_event");

Try it Yourself

Mini Web project with some jQuery functions

In the following web practice many of the jQuery functions explained in this article:

  • The main image is changed by any of three secondary images.
  • We change the color of the main image for any of the 5 colors available at the bottom.
  • Increase or decrease the size of the main image by clicking on any of the two zoom icons located at the bottom of the main image.

Try it Yourself


Tips on SEO and Online Business

Previous Articles