Overview
There are many user actions (events) that a web page can respond to using jQuery. Things such as a mouse click, key press, form submit, or scroll.
The following are some quick examples of the methods used in event interactions. A complete list of events can be found here along with more detailed descriptions of their intended use and syntax.
click() Method
The click event occurs when an HTML element is clicked.
// show an alert when a div is clicked by the user
$('div').click(function() {
alert('The element has been clicked.');
});
dblclick() Method
The dblclick event occurs when an HTML element is double-clicked.
// show an alert when a div is double clicked by the user
$('div').dblclick(function() {
alert('The element has been clicked.');
});
focus() Method
The focus event occurs when an element gets focus when selected by a mouse click or by tabbing to it with the tab keyboard key.
// provide an alert when a form input is made active by the user
$('input').focus(function() {
alert('This input field has focus.');
});
hover() Method
The hover() method specifies two functions to run when the mouse pointer hovers over the selected element, triggering both the mouseenter and mouseleave events.
// set background-color property on hover
$('p').hover(function() {
$(this).css('background-color', 'red');
});
keypress() Method
The keypress event occurs when a keyboard key is pressed down, but not for all keys (e.g. ALT, CTRL, SHIFT, ESC).
// when the user starts to type in a form field, they get an alert
$('input').keypress(function() {
alert('A key was pressed.');
});
on() Method
The on() method attaches one or more event handlers to the selected elements and child elements.
// when the user "clicks" on a div, provide an alert
$('div').on('click', function() {
alert('The element was clicked.');
});
submit() Method
The submit event occurs when an HTML form is submitted.
// on form submit, an alert is provided
$('form').submit(function() {
alert('The form has been submitted.');
});
jQuery Notes:
- To use jQuery on your site, it must first be downloaded from the official jQuery site and linked to in your document <head>, or linked to via a CDN in your document <head>
- It is generally good practice to place your jQuery code/function inside the document load function so that the action takes place ONLY after the document has finished loading
- When using jQuery, single or double quotation marks are acceptable and work identically to one another; choose whichever you prefer, and stay consistent
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.