What is an Event?
Event is nothing but all possible and different actions of visitor's that a webpage can respond to. We have the ability to create dynamic web pages by using events. In general, Events are actions that can be detected by our Web Application.
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
Events handling and manipulating are different for mouse and touch events.
First we discuss about mouse events and basic events.
Lets see some examples of events:
You can use any custom function to do whatever you want to an event when triggered. These custom functions you wrote to happen while an event triggered are called Event handlers.
First of all, we have to run the code using jquery to bind an event. For that we have to create a test page to run and make an event to bind our custom functions.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Demo</title>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<script src="jquery.js"></script>
<script>
// Your code goes here.
</script>
</body>
</html>
To run code as soon as the document is ready to be manipulated, jQuery has a statement known as the ready event:
$(document).ready(function() {
// Your code goes here.
});
or you can use .ready() function like below also:
$(function(){
// Your code goes here.
});
Note: The jQuery library exposes its methods and properties via two properties of the window object called jQuery and $. $ is simply an alias for jQuery and it's often employed because it's shorter and faster to write.
For example, inside the ready event, you can add a click handler to the link:
$(document).ready(function() {
$("a").click(function(event) {
alert("This is a click event!");
});
});
For click and most other events, you can prevent the default behavior by calling event.preventDefault() in the event handler:
$(document).ready(function() {
$("a").click(function(event) {
alert("The link no longer took you to jquery.com, because of a preventDefault() event handler.");
event.preventDefault();
});
});
Binding Event Handlers:
Using the jQuery Event Model, we can establish event handlers on DOM elements with the bind() method as follows −
$(document).ready(function() {
$('div').bind('click', function(event){
alert('Hi there!');
});
});
The full syntax of the bind() command is as follows −
selector.bind(eventType[, eventData], handler)
Following is the description of the parameters −
eventType − A string containing a JavaScript event type, such as click or submit.
eventData − This is 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.
Removing event handlers:
Once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler. There you can use an event handler to remove the existing effect.
jQuery provides the unbind() command to remove an existing event handler. The syntax of unbind() is as follows −
selector.unbind(eventType, handler)
or
selector.unbind(eventType)
Following is the description of the parameters −
eventType − A string containing a JavaScript event type, such as click or submit.
handler − If provided, identifies the specific listener that's to be removed.
Until now, we have learnt how to run and bind an event handler to an event using jQuery. Now we're going to see the events and their handlings.
jQuery provides simple methods for attaching event handlers to selections. When an event occurs, the provided function is executed. Inside the function, this refers to the element that was clicked. The event handling function can receive an event object. This object can be used to determine the nature of the event, and to prevent the event’s default behavior.
Category: Mouse Events
.click() - Bind an event handler to the “click” JavaScript event, or trigger that event on an element.
<div id="target">
click here
</div>
<div id="other">
Trigger the handler
</div>
This event handler can be bound to any <div>
$("#target").click(function() {
alert("Handler for .click() called.");
});
Now if we click on this element, the alert is displayed:
Handler for .click() called.
We can also trigger the event when a different element is clicked:
$("#other").click(function() {
$("#target").click();
});
The click event is only triggered after this exact series of events:
Additional Notes:
.contextmenu() - Bind an event handler to the “contextmenu” JavaScript event, or trigger that event on an element.
This method is a shortcut for .on("contextmenu", handler) in the first two variations, and .trigger("contextmenu") in the third. The contextmenu event is sent to an element when the right button of the mouse is clicked on it, but before the context menu is displayed. In case the context menu key is pressed, the event is triggered on the html element. Any HTML element can receive this event. For example, consider the HTML:
<div id="target">
Right-click here
</div>
The event handler can be bound to the <div> as follows:
$("#target").contextmenu(function() {
alert("Handler for .contextmenu() called.");
});
Now right-clicking on this element displays the alert:
Handler for .contextmenu() called.
To trigger the event manually, call .contextmenu() without an argument:
$("#target").contextmenu();
Additional Notes:
.dblclick() - Bind an event handler to the “dblclick” JavaScript event, or trigger that event on an element.
This method is a shortcut for .on("dblclick", handler) in the first two variations, and .trigger("dblclick") in the third. The dblclick event is sent to an element when the element is double-clicked. Any HTML element can receive this event. For example, consider the HTML:
<div id="target">
Double-click here
</div>
<div id="other">
Trigger the handler
</div>
The event handler can be bound to any <div>:
$("#target").dblclick(function() {
alert("Handler for .dblclick() called.");
});
Now double-clicking on this element displays the alert:
Handler for .dblclick() called.
To trigger the event manually, call .dblclick() without an argument:
$("#other").click(function() {
$("#target").dblclick();
});
After this code executes, (single) clicks on Trigger the handler will also alert the message.
The dblclick event is only triggered after this exact series of events:
It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.
Additional Notes:
.hover() - Bind one or two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.
The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.
Calling $(selector).hover(handlerIn, handlerOut) is shorthand for:
$(selector).mouseenter(handlerIn).mouseleave(handlerOut);
Example:
To add a special style to list items that are being hovered over, try:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hover demo</title>
<style>
ul {
margin-left: 20px;
color: blue;
}
li {
cursor: default;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<ul>
<li>Milk</li>
<li>Bread</li>
<li class="fade">Chips</li>
<li class="fade">Socks</li>
</ul>
<script>
$( "li" ).hover(
function() {
$( this ).append( $( "<span> ***</span>" ) );
}, function() {
$( this ).find( "span:last" ).remove();
}
);
$( "li.fade" ).hover(function() {
$( this ).fadeOut( 100 );
$( this ).fadeIn( 500 );
});
</script>
</body>
</html>
To add a special style to table cells that are being hovered over, try:
$( "td" ).hover(
function() {
$( this ).addClass( "hover" );
}, function() {
$( this ).removeClass( "hover" );
}
);
To unbind the above example use:
$( "td" ).off( "mouseenter mouseleave" );
.hover(handlerInOut) - Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements.
The .hover() method, when passed a single function, will execute that handler for both mouseenter and mouseleave events. This allows the user to use jQuery's various toggle methods within the handler or to respond differently within the handler depending on the event.type.
Calling $(selector).hover(handlerInOut) is shorthand for:
$( selector ).on( "mouseenter mouseleave", handlerInOut );
Example:
Slide the next sibling LI up or down on hover, and toggle a class.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hover demo</title>
<style>
ul {
margin-left: 20px;
color: blue;
}
li {
cursor: default;
}
li.active {
background: black;
color: white;
}
span {
color:red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<ul>
<li>Milk</li>
<li>White</li>
<li>Carrots</li>
<li>Orange</li>
<li>Broccoli</li>
<li>Green</li>
</ul>
<script>
$( "li" )
.filter( ":odd" )
.hide()
.end()
.filter( ":even" )
.hover(function() {
$( this )
.toggleClass( "active" )
.next()
.stop( true, true )
.slideToggle();
});
</script>
</body>
</html>
.mousedown() - Bind an event handler to the “mousedown” JavaScript event, or trigger that event on an element.
This method is a shortcut for .on("mousedown", handler) in the first variation, and .trigger("mousedown") in the second.
The mousedown event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed. Any HTML element can receive this event.
For example, consider the HTML:
<div id="target">
Click here
</div>
<div id="other">
Trigger the handler
</div>
The event handler can be bound to any <div>:
$( "#target" ).mousedown(function() {
alert( "Handler for .mousedown() called." );
});
Now if we click on this element, the alert is displayed:
Handler for .mousedown() called.
We can also trigger the event when a different element is clicked:
$( "#other" ).click(function() {
$( "#target" ).mousedown();
});
After this code executes, clicks on Trigger the handler will also append the message.
The mouseenter event differs from mouseover in the way it handles event bubbling. If mouseover were used in this example, then when the mouse pointer moved over the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseenter event, on the other hand, only triggers its handler when the mouse enters the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse enters the Outer element, but not the Inner element.
Additional Notes:
.mouseleave() - Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.
This method is a shortcut for .on('mouseleave', handler) in the first two variations, and .trigger('mouseleave') in the third.
The mouseleave JavaScript event is proprietary to Internet Explorer. Because of the event's general utility, jQuery simulates this event so that it can be used regardless of browser. This event is sent to an element when the mouse pointer leaves the element. Any HTML element can receive this event.
For example, consider the HTML:
<div id="outer">
Outer
<div id="inner">
Inner
</div>
</div>
<div id="other">
Trigger the handler
</div>
<div id="log"></div>
The event handler can be bound to any element:
$( "#outer" ).mouseleave(function() {
$( "#log" ).append( "<div>Handler for .mouseleave() called.</div>" );
});
Now when the mouse pointer moves out of the Outer <div>, the message is appended to <div id="log">. You can also trigger the event when another element is clicked:
$( "#other" ).click(function() {
$( "#outer" ).mouseleave();
});
After this code executes, clicks on Trigger the handler will also append the message.
The mouseleave event differs from mouseout in the way it handles event bubbling. If mouseout were used in this example, then when the mouse pointer moved out of the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseleave event, on the other hand, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse leaves the Outer element, but not the Inner element.
Additional Notes:
.mousemove() - Bind an event handler to the “mousemove” JavaScript event, or trigger that event on an element.
This method is a shortcut for .on("mousemove", handler) in the first two variations, and .trigger("mousemove") in the third.
The mousemove event is sent to an element when the mouse pointer moves inside the element. Any HTML element can receive this event.
For example, consider the HTML:
<div id="target">
Move here
</div>
<div id="other">
Trigger the handler
</div>
<div id="log"></div>
The event handler can be bound to the target:
$("#target").mousemove(function( event ) {
var msg = "Handler for .mousemove() called at ";
msg += event.pageX + ", " + event.pageY;
$("#log").append("<div>" + msg + "</div>");
});
Now when the mouse pointer moves within the target button, the messages are appended to <div id="log">:
Handler for .mousemove() called at (399, 48)
Handler for .mousemove() called at (398, 46)
Handler for .mousemove() called at (397, 44)
Handler for .mousemove() called at (396, 42)
To trigger the event manually, apply .mousemove() without an argument:
$("#other").click(function() {
$("#target").mousemove();
});
After this code executes, clicks on Trigger the handler will also append the message.
This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves out of the Inner element in this example, a mouseout event will be sent to that, then trickle up to Outer. This can trigger the bound mouseout handler at inopportune times. See the discussion for .mouseleave() for a useful alternative.
Additional Notes:
.mouseover() - Bind an event handler to the “mouseover” JavaScript event, or trigger that event on an element.
This method is a shortcut for .on("mouseover", handler) in the first two variations, and .trigger("mouseover") in the third.
The mouseover event is sent to an element when the mouse pointer enters the element. Any HTML element can receive this event.
For example, consider the HTML:
<div id="outer">
Outer
<div id="inner">
Inner
</div>
</div>
<div id="other">
Trigger the handler
</div>
<div id="log"></div>
The event handler can be bound to any element:
$("#outer").mouseover(function() {
$("#log").append( "<div>Handler for .mouseover() called.</div>" );
});
Now when the mouse pointer moves over the Outer <div>, the message is appended to <div id="log">. We can also trigger the event when another element is clicked:
$( "#other" ).click(function() {
$( "#outer" ).mouseover();
});
After this code executes, clicks on Trigger the handler will also append the message.
This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves over the Inner element in this example, a mouseover event will be sent to that, then trickle up to Outer. This can trigger our bound mouseover handler at inopportune times. See the discussion for .mouseenter() for a useful alternative.
Additional Notes:
.mouseup() - Bind an event handler to the “mouseup” JavaScript event, or trigger that event on an element.
This method is a shortcut for .on('mouseup', handler) in the first variation, and .trigger('mouseup') in the second.
The mouseup event is sent to an element when the mouse pointer is over the element, and the mouse button is released. Any HTML element can receive this event.
For example, consider the HTML:
<div id="target">
Click here
</div>
<div id="other">
Trigger the handler
</div>
The event handler can be bound to any <div>:
$("#target").mouseup(function() {
alert("Handler for .mouseup() called.");
});
Now if we click on this element, the alert is displayed:
Handler for .mouseup() called.
We can also trigger the event when a different element is clicked:
$("#other").click(function() {
$("#target").mouseup();
});
After this code executes, clicks on Trigger the handler will also alert the message.
If the user clicks outside an element, drags onto it, and releases the button, this is still counted as a mouseup event. This sequence of actions is not treated as a button press in most user interfaces, so it is usually better to use the click event unless we know that the mouseup event is preferable for a particular situation.
Additional Notes:
.toggle() - Bind two or more handlers to the matched elements, to be executed on alternate clicks.
Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 1.9. jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed.
The .toggle() method binds a handler for the click event, so the rules outlined for the triggering of click apply here as well.
For example, consider the HTML:
<div id="target">
Click here
</div>
Event handlers can then be bound to the <div>:
$("#target" ).toggle(function() {
alert("First handler for .toggle() called.");
}, function() {
alert("Second handler for .toggle() called.");
});
As the element is clicked repeatedly, the messages alternate:
First handler for .toggle() called.
Second handler for .toggle() called.
First handler for .toggle() called.
Second handler for .toggle() called.
First handler for .toggle() called.
If more than two handlers are provided, .toggle() will cycle among all of them. For example, if there are three handlers, then the first handler will be called on the first click, the fourth click, the seventh click, and so on.
The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting. For example, .toggle() is not guaranteed to work correctly if applied twice to the same element. Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element.
jQuery Mobile Touch Events:
Touch events are nothing but the actions that are performed when user touches the screen.
Following events list are some of the touch events which are supported by the jQuery Mobile:
The tap event is triggered when the user taps on an element.
The below example describes use of tap event in the jQuery Mobile Framework:
The following example says: When a tap event fires on a <p> element; hide the current <p> element:
<!DOCTYPE html>
<head>
<title>Tap Event</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script>
$(document).on("pagecreate","#page1",function(){
$("p").on("tap",function(){
$(this).hide();
});
});
</script>
</head>
<body>
<div data-role="page" id="page1">
<div data-role="header">
<h2>Header</h2>
</div>
<div data-role="main" class="ui-content">
<p>This line will disappear, if you tap on it.</p>
</div>
<div data-role="footer">
<h2>Footer</h2>
</div>
</div>
</body>
</html>
2. Taphold event:
Fires when user tap on an element and hold for couple of seconds by using id of the page to specify event and on() method attaches the event handlers.
The below example describes use of taphold event in the jQuery Mobile Framework:
Using the above eaxmple we will replace the tap event to taphold event to take effect.
<!DOCTYPE html>
<head>
<title>Taphold Event</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script>
$(document).on("pagecreate","#page1",function(){
$("p").on("taphold",function(){
$(this).hide();
});
});
</script>
</head>
<body>
<div data-role="page" id="page1">
<div data-role="header">
<h2>Header</h2>
</div>
<div data-role="main" class="ui-content">
<p>This line will disappear, if you tap on it.</p>
</div>
<div data-role="footer">
<h2>Footer</h2>
</div>
</div>
</body>
</html>
3. Swipe event:
The swipe event is triggered when the user drag horizontally by more than 30px over an element by using id of the page to specify event and on() method attaches the event handlers.
The below example describes use of swipe event in the jQuery Mobile Framework:
<!DOCTYPE html>
<head>
<title>Swipe Event</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script>
$(document).on("pagecreate","#page1",function(){
$("p").on("swipe",function(){
$("span").text("swipe event occurred!!!");
});
});
</script>
</head>
<body>
<div data-role="page" id="page1">
<div data-role="header">
<h2>Header</h2>
</div>
<div data-role="main" class="ui-content">
<p>It will display the text when you swipe here.</p>
<span style="color:orange"></span>
</div>
<div data-role="footer">
<h2>Footer</h2>
</div>
</div>
</body>
</html>
4. Swipeleft event:
The swipeleft event is triggered when user drag more than 30px over an element in the left direction by using id of the page to specify event and on() method attaches the event handlers.
The below example describes use of swipeleft event in the jQuery Mobile Framework:
<!DOCTYPE html>
<head>
<title>Swipeleft Event</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script>
$(document).on("pagecreate","#page1",function(){
$("p").on("swipeleft",function(){
$("span").text("swipe event occurred!!!");
});
});
</script>
</head>
<body>
<div data-role="page" id="page1">
<div data-role="header">
<h2>Header</h2>
</div>
<div data-role="main" class="ui-content">
<p>It will display the text when you swipe left side.</p>
<span style="color:orange"></span>
</div>
<div data-role="footer">
<h2>Footer</h2>
</div>
</div>
</body>
</html>
The swiperight event is triggered when user drag more than 30px over an element in the right direction by using id of the page to specify event and on() method attaches the event handlers.
The below example describes use of swiperight event in the jQuery Mobile Framework:
<!DOCTYPE html>
<head>
<title>Swiperight Event</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script>
$(document).on("pagecreate","#page1",function(){
$("p").on("swiperight",function(){
$("span").text("swipe event occurred!!!");
});
});
</script>
</head>
<body>
<div data-role="page" id="page1">
<div data-role="header">
<h2>Header</h2>
</div>
<div data-role="main" class="ui-content">
<p>It will display the text when you swipe right side.</p>
<span style="color:orange"></span>
</div>
<div data-role="footer">
<h2>Footer</h2>
</div>
</div>
</body>
</html>