Thursday, May 7, 2020

Event Handling in JQuery - The definitive guide



Hello guys! Welcome to a new section of my tutorial on jQuery. In this tutorial, we are going to be discussing about event handling in jQuery.

Read through this tutorial guide very carefully and ask questions where necessary. I promise to attend to your questions as soon as possible.

By making use of events, we have the ability to create a dynamic webpages. Events are actions that can be detected by your web browser.

The following below are examples of events -

  • A webpage loading
  • A keystroke on your keyboard
  • A mouse click
  • HTML form submission
  • Taking a mouse over an element

When these events are triggered, you can then use a custom function to do whatever you want with the event. This custom functions are called the Event Handlers.

Binding Event Handlers

Using the jQuery event model, we can establish event handlers on DoM elements with the bind() method.

Syntax

Below is the syntax to use this method -

selector.bind( eventType[,     eventData],     handler )

Parameter Details

The following below is the description of all the parameters -

  • eventType - String containing a JavaScript event type, such as click or submit.
  • eventData - This optional parameter is a map of data that will be passed to the event handler.
  • handler - A function to execute each time the event is triggered.

Example

Following below is an example on th usage of this method -

<html>
     <head>
          <title>jQuery Example</title>
          <script  type = "text/javascript"   
               src = "https//ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js">               
          </script>  

          <script  type = "text/javascript">
               $( document ).ready( function( )  {
                    $( 'div' ).bind( 'click',   function( event )  {
                         alert( 'Hello World!' );
                    } );
               } );
          </script>

          <style>
               .div { 
                    width: 60px;  margin: 10px;  padding: 10px;  border: 3px solid #666; 
               }
          </style>
     </head>

     <body>
          <p>Click on any square to see result:</p>
                   
          <div  class = "div" style = "background-color: yellow; ">Five</div>
          <div  class = "div" style = "background-color: blue;">Six</div>
          <div  class = "div" style = "background-color: purple;">Seven</div>
     </body>
</html>

The above code will cause the division element to respond to the click event; when a user clicks inside this division thereafter, the alert will pop-up.

You can try the above code out to see the result for yourselves.


Removing Event Handlers

Once an event handler is established, it remains in effect as long as the page it was established upon continues existing. There may be a need for you to remove the event handler.

jQuery makes available the unbind( ) method to remove an existing event handler.

Syntax

Below is the syntax to use this method -

selector.unbind( eventType,     handler )

or

selector.unbind( eventType )

Parameter Details

The following below is the description of all the parameters -

  • eventType - String containing a JavaScript event type, such as click or submit.
  • handler - If provided identifies the specific event that's to be removed.


Event Types

The following list below are the recommended event types which you can bind using jQuery -

Sr.No.Event Type & Description
1
blur
Occurs when the element loses focus.
2
change
Occurs when the element changes.
3
click
Occurs when a mouse click.
4
dblclick
Occurs when a mouse double-click.
5
error
Occurs when there is an error in loading or unloading etc.
6
focus
Occurs when the element gets focus.
7
keydown
Occurs when key is pressed.
8
keypress
Occurs when key is pressed and released.
9
keyup
Occurs when key is released.
10
load
Occurs when document is loaded.
11
mousedown
Occurs when mouse button is pressed.
12
mouseenter
Occurs when mouse enters in an element region.
13
mouseleave
Occurs when mouse leaves an element region.
14
mousemove
Occurs when mouse pointer moves.
15
mouseout
Occurs when mouse pointer moves out of an element.
16
mouseover
Occurs when mouse pointer moves over an element.
17
mouseup
Occurs when mouse button is released.
18
resize
Occurs when window is resized.
19
scroll
Occurs when window is scrolled.
20
select
Occurs when a text is selected.
21
submit
Occurs when form is submitted.
22
unload
Occurs when documents is unloaded


The Event Object

The callback function takes a single parameter; when the handler is called, the JavaScript event object will be passed through it.

The event object is often unnecessary and the parameter is omitted,  as sufficient context is normally available when the handler is bound to know exactly what needs to be done whenever the handler is triggered, however there are certain attributes will we would need to access.


The Event Attributes

The following event attributes are available and safe to access in a platform independent way -

Sr.No.Property & Description
1
altKey
Set to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled Option on most Mac keyboards.
2
ctrlKey
Set to true if the Ctrl key was pressed when the event was triggered, false if not.
3
data
The value, if any, passed as the second parameter to the bind() command when the handler was established.
4
keyCode
For keyup and keydown events, this returns the key that was pressed.
5
metaKey
Set to true if the Meta key was pressed when the event was triggered, false if not. The Meta key is the Ctrl key on PCs and the Command key on Macs.
6
pageX
For mouse events, specifies the horizontal coordinate of the event relative from the page origin.
7
pageY
For mouse events, specifies the vertical coordinate of the event relative from the page origin.
8
relatedTarget
For some mouse events, identifies the element that the cursor left or entered when the event was triggered.
9
screenX
For mouse events, specifies the horizontal coordinate of the event relative from the screen origin.
10
screenY
For mouse events, specifies the vertical coordinate of the event relative from the screen origin.
11
shiftKey
Set to true if the Shift key was pressed when the event was triggered, false if not.
12
target
Identifies the element for which the event was triggered.
13
timeStamp
The timestamp (in milliseconds) when the event was created.
14
type
For all events, specifies the type of event that was triggered (for example, click).
15
which
For keyboard events, specifies the numeric code for the key that caused the event, and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3 for right).


<html>
     <head>
          <title>jQuery Example</title>
          <script  type = "text/javascript"   
               src = "https//ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js">               
          </script>  

          <script  type = "text/javascript">
               $( document ).ready( function( )  {
                    $( 'div' ).bind( 'click',   function( event )  {
                         alert( 'Event type is'  +  event.type );
                         alert( 'pageX :  '  +  event.pageX );
                         alert( 'pageY :  '  +  event.pageY );
                         alert( 'Target :  '  +  event.target.innerHTML );            
                    } );
               } );
          </script>

          <style>
               .div { 
                    width: 60px;  margin: 10px;  padding: 10px;  border: 3px solid #666; 
               }
          </style>
     </head>

     <body>
          <p>Click on any square to see result:</p>
                   
          <div  class = "div" style = "background-color: yellow; ">Five</div>
          <div  class = "div" style = "background-color: blue;">Six</div>
          <div  class = "div" style = "background-color: purple;">Seven</div>
     </body>
</html>

You can try the above code out to see the result for yourselves.


Event Methods
Below is a list of methods which can be called on an Event Object -

Sr.No.Method & Description
1preventDefault()
Prevents the browser from executing the default action.
2isDefaultPrevented()
Returns whether event.preventDefault() was ever called on this event object.
3stopPropagation()
Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.
4isPropagationStopped()
Returns whether event.stopPropagation() was ever called on this event object.
5stopImmediatePropagation()
Stops the rest of the handlers from being executed.
6isImmediatePropagationStopped()
Returns whether event.stopImmediatePropagation() was ever called on this event object.


The Event Manipulation Methods
The following table below lists down important event related methods -

Sr.No.Method & Description
1bind( type, [data], fn )
Binds a handler to one or more events (like click) for each matched element. Can also bind custom events.
2off( events [, selector ] [, handler(eventObject) ] )
This does the opposite of live, it removes a bound live event.
3hover( over, out )
Simulates hovering for example moving the mouse on, and off, an object.
4on( events [, selector ] [, data ], handler )
Binds a handler to an event (like click) for all current − and future − matched element. Can also bind custom events.
5one( type, [data], fn )
Binds a handler to one or more events to be executed once for each matched element.
6ready( fn )
Binds a function to be executed whenever the DOM is ready to be traversed and manipulated.
7trigger( event, [data] )
Trigger an event on every matched element.
8triggerHandler( event, [data] )
Triggers all bound event handlers on an element.
9unbind( [type], [fn] )
This does the opposite of bind, it removes bound events from each of the matched elements.


Event Helper Methods
jQuery provides a set of event helper functions which can be used either to trigger an event or bind any event type listed above.

The Trigger Methods
The following below is an example which will trigger the blur event on all paragraphs -

$( "p" ).blur( );

Binding Methods
Following is an example which will bind a click to all <div> -

$( "div" ).click( function( ) {
     // Do some coding here 
} );


Here is a complete list of the support methods available in jQuery -

Sr.No.Method & Description
1
blur( )
Triggers the blur event of each matched element.
2
blur( fn )
Bind a function to the blur event of each matched element.
3
change( )
Triggers the change event of each matched element.
4
change( fn )
Binds a function to the change event of each matched element.
5
click( )
Triggers the click event of each matched element.
6
click( fn )
Binds a function to the click event of each matched element.
7
dblclick( )
Triggers the dblclick event of each matched element.
8
dblclick( fn )
Binds a function to the dblclick event of each matched element.
9
error( )
Triggers the error event of each matched element.
10
error( fn )
Binds a function to the error event of each matched element.
11
focus( )
Triggers the focus event of each matched element.
12
focus( fn )
Binds a function to the focus event of each matched element.
13
keydown( )
Triggers the keydown event of each matched element.
14
keydown( fn )
Bind a function to the keydown event of each matched element.
15
keypress( )
Triggers the keypress event of each matched element.
16
keypress( fn )
Binds a function to the keypress event of each matched element.
17
keyup( )
Triggers the keyup event of each matched element.
18
keyup( fn )
Bind a function to the keyup event of each matched element.
19
load( fn )
Binds a function to the load event of each matched element.
20
mousedown( fn )
Binds a function to the mousedown event of each matched element.
21
mouseenter( fn )
Bind a function to the mouseenter event of each matched element.
22
mouseleave( fn )
Bind a function to the mouseleave event of each matched element.
23
mousemove( fn )
Bind a function to the mousemove event of each matched element.
24
mouseout( fn )
Bind a function to the mouseout event of each matched element.
25
mouseover( fn )
Bind a function to the mouseover event of each matched element.
26
mouseup( fn )
Bind a function to the mouseup event of each matched element.
27
resize( fn )
Bind a function to the resize event of each matched element.
28
scroll( fn )
Bind a function to the scroll event of each matched element.
29
select( )
Trigger the select event of each matched element.
30
select( fn )
Bind a function to the select event of each matched element.
31
submit( )
Trigger the submit event of each matched element.
32
submit( fn )
Bind a function to the submit event of each matched element.
33
unload( fn )
Binds a function to the unload event of each matched element.

Alright guys! We have come to the end of this tutorial post. In my next tutorial, i will be using few examples to demonstrate the usage of the event methods listed above.

Feel free to ask your questions where necessary and i will attend to them as soon as possible.

Follow us on our various social media platforms available. You can also subscribe to our email list to get our tutorials delivered directly to your emails. Thanks for reading and bye for now.
Share:

0 comments:

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.