Monday 26 July 2021

Third Day: jQuery Events

jQuery has made it easier to use events on HTML pages. Lets start with basics with what, why and how?

What are Events?

Everything you do on web page, including moving of mouse to hit of keyboard are considered to be actions and Events are bound to react on those actions.

All Events are reflection of action, that tells something happened to react on.

Examples:
  1. Click of mouse on any element.
  2. Taking mouse over an element.
  3. Writing something on element.
  4. Selecting something like check-box or radio button.
 While working with events you might hear some words like runs, initiated, triggered, fires, etc., these are synonyms stating that event has been occurred on some action.

Events can be classified into four categories with few examples as:

Document/Window Events Mouse Events Keyboard Events Form Events
load (on page load completed) click (on mouse click or keyboard enter on element) keypress (on hit of key from keyboard) submit (on submit form through enter or submit button click)
resize (on browser window size changed) dblclick (on mouse double click) keydown (on press key from keyboard) change (on change on state, works with form elements)
scroll (on scrolling on page) mouseenter (when mouse enters element perimeter/boundary) keyup (on release of key after pressing) focus (on taking focus on element either through mouse or keyboard)
unload (on refreshing/closing page) mouseleave (when mouse leaves element perimeter/boundart)
blur (on taking focus out from element either through mouse or keyboard)

Here is a reference link from official jQuery site for list of event methods present in jQuery.

jQuery Syntax For Event Methods

In jQuery, most DOM events have an equivalent jQuery method. 

To assign a click event to all paragraphs on a page, you can do this: 

$("p").click(); 

The next step is to define what should happen when the event fires. You must pass a function to the event: 

$("p").click(function(){  
        // some action to occur in function 
});

Commonly Used jQuery Event Methods

 

 $(document).ready()

 

The $(document).ready() method allows us to execute a function when the document is fully loaded. This event is already explained in the jQuery Syntax chapter. 


click()

 

The click() method attaches an event handler function to an HTML element.
The function is executed when the user clicks on the HTML element.
The following example says: When a click event fires on a <p> element; hide the current <p> element:

$("p").click(function(){
    $(this).hide();
});