Events

JQuery makes it easier to response when user interacts with the web page. For example, we can perform several tasks when they click somewhere, scroll the document, hover on field or anything like that. Whenever user interacts with the web page, an event is occurred. We can use event handling to execute our code.

Mouse events

These are the events that are instantiated as soon as the user activates any of the functions related to the mouse. In the following sections, we will cover the description of each mouse event.

.click()

The click event takes a DOM object and calls the function if or when it is clicked by the user.

Parameters

The click event receives a callback function.

Returns

This returns the response generated by the function called on click.

Description

The click event uses the ID to get what the user has clicked on and accordingly calls its respective function defined inside the body.

Here is an example of its usage.

HTML Code:

<div id="clicked">
  //function to be called after clicked
</div>

jQuery Code:

$( "#clicked" ).click(function() {
  alert( "Function for .click() called." );
});

.dblclick()

We can attach a handler to the double-click event of an HTML element using the .dblclick() jQuery method.

Parameters

The dbclick event receives a callback function.

Returns

This returns the response generated by the function called on double click.

Description

The dblclick event uses the ID to get what the user had double clicked on and accordingly calls its respective function.

Here is an example of its usage.

HTML Code:

<div id="clicked">
  // function to be called after clicked
</div>

jQuery Code:

$( "#clicked" ).dblclick(function() {
  alert( "Function for .dblclick() called." );
});

.hover()

The hover event uses the ID to get what the user had his mouse on and accordingly calls its respective function.

Parameters

The hover event receives a callback function.

Returns

This returns the response generated by the function called on hover.

Description

The hover event uses the ID to get what the user had his mouse on and accordingly calls its respective function.

Here is an example of its usage.

HTML Code:

<ul>
  <li>Lahore</li>
  <li>Karachi</li>
  <li>Peshawar</li>
  <li>Sialkot</li>
</ul>

jQuery Code:

$( "li" ).hover(
  function() {
    $( this ).append( $( "<span> (*)</span>" ) ); // "this" is used to access the current object itself
  }, function() {
    $( this ).find( "span:first" ).remove();
  }
);

.mousedown()

The .mousedown event is activated when the user left-clicks on the mouse and highlights a specific text.

Parameters

The .mousedown() function which gets executed when the element is clicked.

Returns

This returns the response generated by the function called on click.

Description

The event is activated when the user left-clicks and highlights some specific text.

Here is an example of its usage.

HTML Code:

<div id="myTarget">
  Click here
</div>

jQuery Code:

$( "#myTarget" ).mousedown(function() {
  alert( "Function for .mousedown() called." );
});

.mouseenter()

The event is activated when the mouse is hovered over the selected text and a function is called accordingly.

Parameters

The mouseenter event receives a callback function.

Returns

This returns the response generated by the function called on mouse enter.

Description

This event is activated when the mouse is hovered over the selected text and a function is called accordingly. The event related to the mouseenter() is fired only once, so it does not matter if you hold the cursor over an element, the function assigned through this function is executed only once.

Here is an example of its usage.

HTML Code:

<div id="external">
  External
  <div id="internal">
    Internal
  </div>
</div>
<div id="myLog"></div>

jQuery Code:

$( "#external" ).mouseenter(function() {
  $( "#myLog" ).append( "<p>Function for .mouseenter() called.</p>" );
});

.mouseleave()

The .mouseleave event is activated when the cursor is moved away from the HTML element.

Parameters

The mouseleave event receives a callback function.

Returns

This returns the response generated by the function called on clicked.

Description

The event is activated when the mouse is left. The function is called accordingly.

Here is an example of its usage.

HTML Code:

<div id="external">
  External
  <div id="internal">
    Internal
  </div>
</div>
<div id="myLog"></div>

jQuery Code:

$( "#external" ).mouseleave(function() {
  $( "#myLog" ).append( "<p> Function for .mouseleave() called.</p>" );
});

.mousemove()

The .mousemove event is triggered when the mouse is being moved within an element.

Parameters

The mousemove event receives a callback function.

Returns

This returns the response generated by the function called on mouse move.

Description

This event is triggered when the mouse is being moved within an element.

Here is an example of its usage.

HTML Code:

<div id="myTarget">
  Move here
</div>
<div id="other">
  Trigger the Function
</div>
<div id="myLog"></div>

jQuery Code:

$( "#myTarget" ).mousemove(function( event ) {
  // the event keyword identifies the mousemove event in the case of this example
  var msg = "Function for .mousemove() called at ";
  msg += event.pageX + ", " + event.pageY;
  $( "#myLog" ).append( "<div>" + msg + "</div>" );
});

.mouseout()

The .mouseout event is triggered when the mouse pointer leaves the boundaries of the element. Any HTML element can be bound to this event.

Parameters

The mouseout event receives a callback function.

Returns

This returns the response generated by the function called when the mouse moves out of the targeted element.

Description

The mouseout event is triggered when the mouse pointer leaves the element.

Here is an example of its usage.

Required HTML Code:

<div id="external">
  External
  <div id="internal">
    Internal
  </div>
</div>
<div id="other">
  Trigger the Function
</div>
<div id="myLog"></div>

Required jQuery Code:

$( "#external" ).mouseout(function() {
  $( "#myLog" ).append( "<p>Function for .mouseout() called.</p>" );
});

.toggle()

This .toggle() function is used to bind multiple handlers to matching elements that are executed on alternate clicks.

Parameters

The parameters of the toggle() function are duration, easing, and callback.

The duration parameter is optional and is used to specify the speed of the hide and show effect. The possible values are fast, slow, and milliseconds. The default is 400 ms.

The easing parameter is optional and is used to specify the easing() function that is to be used for animation. The default value is string.

The callback parameter too is optional and is used to specify the function that is to be called once the animation is complete.

Returns

This returns the output of the function that is called.

Description

This function is used to check the visibility of an element and then alternate between the hide() and show() methods. The callback is always fired once the animation is complete and only once for the element that finds a match.

Here is an example of its usage.

Required HTML Code:

<ul>
  <li>Mercury</li>
  <li>Venus</li>
  <li>Earth</li>
  <li>Mars</li>
</ul>

Required jQuery Code:

$(document).ready(function() {
  $("ul").click(function() {
    $("li").toggle("slow", function() {
    });
  });
});

Keyboard events

The keyboard events are triggered on Keyboard functions, for example, when a button/key is pressed or released, and so on. Keyboard events can be controlled with the following built-in jQuery functions. The available functions are KeyDown, KeyPress, and KeyUp.

The only practical difference between KeyDown and KeyPress is that KeyPress relays the character resulting from a KeyPress event and is only called if there is one.

For example, if you press A on your keyboard, you'll get this sequence of events:

  • KeyDown: KeyCode=Keys.A, KeyData=Keys.A, Modifiers=Keys.None
  • KeyPress: KeyChar='a'
  • KeyUp: KeyCode=Keys.A

.keydown()

The keydown event is instantiated when a key is pressed by the user.

Parameters

The keydown event sends the key pressed as a parameter.

Returns

This returns the output of the function that is called when a key is pushed down.

Description

The keydown event is instantiated when the user presses a key, which calls the function to be executed.

Here is an example of its usage.

Required HTML Code:

<form>
  <input id="myTarget" type="text" value="KeyPress">
</form>

Required jQuery Code:

$( "#myTarget" ).keydown(function() {
  alert( "Function for .keydown() called." );
});

The preceding sample code selects the div element with the myTarget ID and triggers the alert function when a key is pressed down.

.keypress()

The keypress event is instantiated when a key is pressed by the user.

Parameters

This sends the key pressed as parameter.

Returns

This returns the output of the function called by the key press.

Description

The keypress event is instantiated when the user presses a key, which calls the function to be executed.

Here is an example of its usage.

Required HTML Code:

<form>
  <fieldset>
    <input id="myTarget" type="text" value="Tomato">
  </fieldset>
</form>

Required jQuery Code:

$( "#myTarget" ).keypress(function() {
  console.myLog( "Function for .keypress() called." );
});

The preceding sample code selects the div element with the myTarget ID and triggers the alert function when a key is pressed.

.keyup()

The keyup event occurs when the key that is pressed is released by the user.

Parameters

This sends the key pressed as a parameter.

Returns

This returns the output of the function that is called when key is released.

Description

The event occurs when the key pressed is released by the user.

Here is an example of its usage.

Required HTML Code:

<form>
  <input id="myTarget" type="text" value="Hello there">
</form>

Required jQuery Code:

$( "#myTarget" ).keyup(function() {
  alert( "Function for .keyup() called." );
});

The preceding sample code selects the div with the myTarget ID and triggers the alert function when a key is released.

Form events

Form events are when elements inside a form are bound to jQuery. These events are helpful when it comes to processing data entered via forms. These events can be used on elements inside the <form> tags. We will now cover the description of each form event.

submit()

The submit event, as the name suggests, is fired when a form is submitted.

Its syntax is $(selector).submit(function).

Parameters

The parameter taken is the function that is to be run once the form is submitted.

Returns

This event does not return anything.

Description

The submit() function is a form event. It is used to bind form elements with a function that needs to be called whenever a form is submitted.

Required HTML Code:

<form action="">
  User ID: <input type="text" name="UsrID" value="KA112"><br>
  Password: <input type="password" name="password" value="Password"><br>
  <input type="submit" value="Submit">
</form>

Required JQuery Code:

$(document).ready(function() {
  $("form").submit(function() {
    alert("Form Submitted!");
  });
});

change()

The change event is fired whenever the value of an element in a form changes.

Its syntax is $(selector).change(function).

Parameters

The parameter taken is the function that is to be run once the value of the selected element changes.

Returns


This event does not return anything.

Description

This event is used to bind the event to a function that needs to be called whenever a value inside a form element changes. This function works only on the <input>, <textarea>, and <select> elements.

Required HTML Code:

<select name="ShadesOfGreen">
  <option value="Jade">Jade</option>
  <option value="Mint">Mint</option>
  <option value="Emerald">Emerald</option>
  <option value="Moss">Moss</option>
</select>

Required JQuery Code:

$(document).ready(function() {
  $("select").change(function() {
    alert("Option Changed");
  });
});

blur()

The blur event is fired whenever an element in a form loses its focus and the user moves to the next element in the form.

Its syntax is $(selector).blur(function).

Parameters

The parameter taken is the function that is to be run once the element loses focus.

Returns

This event does not return anything.

Description

The blur event is used to call a function whenever an element loses its focus.

Required HTML Code:

User ID: <input type="text">
Gender: <select name="Gender">
  <option value="Male">Male</option>
  <option value="Female">Female</option>
</select>

Required JQuery Code:

$(document).ready(function() {
  $("input").blur(function() {
    alert("User ID lost foucs");
  });
});

focus()

The focus event is fired whenever an element in a form gets its focus.

Its syntax is $(selector).focus(function).

Parameters

The parameter taken is the function that is to be run once the element is in focus.

Returns

This event does not return anything.

Description

The focus event is used to call a function whenever an element is in focus. An element is generally in focus when we select it with the mouse or use the Tab key to navigate to it. This event is triggered only when the specified element is in focus and not the element's children.

The focus event is generally used with the blur event.

Required HTML Code:

User ID: <input type="text" name="UsrID"><br>
Email ID: <input type="text" name="emailID">

Required JQuery Code:

$(document).ready(function() {
  $("input").focus(function() {
    $(this).css("background-color", "#cccccc");
  });
  $("input").blur(function() {
    $(this).css("background-color", "#ffffff");
  });
});

focusin()

This event is fired whenever an element or its child is in focus.

Its syntax is $(selector).focusin(function).

Parameters

The parameter taken is the function that is to be run once the element is in focus.

Returns

This event does not return anything.

Description

The focusin event is used to call a function whenever an element is in focus. This event is also called whenever a child element is in focus.

Required HTML Code:

<div>
  Name: <input type="text" name="fullname"><br>
  Email: <input type="text" name="email">
</div>

Required JQuery Code:

$(document).ready(function() {
  $("div").focusin(function() {
    $(this).css("background-color", "#cccccc");
  });
});

focusout()

The focusout event is fired whenever an element or its child is out of focus.

Its syntax is $(selector).focusout(function).

Parameters

The parameter taken is the function that is to be run once the element is in focus.

Returns

This event does not return anything.

Description

This event is fired whenever an element or its child loses its focus. This event is generally used along with the focusin event.

Required HTML Code:

<div>
  Name: <input type="text" name="fullname"><br>
  Email: <input type="text" name="email">
</div>

Required JQuery Code:

$(document).ready(function() {
  $("div").focusin(function() {
    $(this).css("background-color", "#cccccc");
  });
  $("div").focusout(function() {
    $(this).css("background-color", "#ffffff");
  });
});

Document events

Document events are generally fired whenever a document is loaded. In the following sections, we will cover the description of each document event.

resize()

The resize event is fired whenever the user resizes the window. Its syntax is as follows:

$(selector).resize(function)

Parameters

The parameter taken is the function that is to be run once the window is resized.

Returns

This event does not return anything.

Description

The resize event is used to call a function when the user resizes the window.

Required HTML Code:

<p></p>

Required JQuery Code:

$(document).ready(function() {
  $(window).resize(function() {
    $("p").text("Window resized!!");
  });
}); 

scroll()

The scroll event is fired whenever the user scrolls in the (scrollable) element. We can use this event to bind it to a function. Its syntax is as follows:

$(selector).scroll(function)

Parameters

The parameter taken is the function that is to be run once the user scrolls on the element.

Returns

This event does not return anything.

Description

The scroll event is fired whenever the user scrolls in an element.

Required HTML Code:

<div style="border:1px solid black;width:200px;height:100px;overflow:scroll;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur vehicula ultrices nulla vel facilisis. Curabitur elementum lorem non massa porttitor accumsan. Cras eu leo tincidunt, pulvinar neque et, tempus dolor. Nam condimentum nisl vel quam posuere, vitae malesuada nunc molestie. Aliquam pulvinar diam eu magna sagittis efficitur. Vestibulum tempor, leo accumsan maximus hendrerit, ex nisi rutrum sapien, nec ultricies tellus nisl ac lacus. Phasellus sed ligula augue.
</div>

<p></p>

Required JQuery Code:

$(document).ready(function() {
  $("div").scroll(function() {
    $("p").text( "Text Scrolled!");
  });
});
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.114.85