Module 2.1.
Before Start
The following contents are the notes I took when learning jQuery on Edx.
Mainly for front-End Web developers, check here to get more details.
CONTENTS
Three parts:
- Adding jQuery to web pages
- Managing content, events and effects
- Asynchronous operations and Ajax calls
Module2 : Managing content, events and effects
Module2 includes six parts:
- Event handlers
- Modifying elements
- Registering event handlers
- Adding new elements
- Animations
- Removing, replacing and cloning
Let’s get to know something about the first three parts.
Event handlers
Event object:
Beyond just the object that raised the event, jQuery (and JavaScript) also pass an
event
object to the event handler.This object can be used to determine additional information, such as where the mouse was when the user performed the operation.
Example:
// Write out the x/y coordinates of the mouse on click $('button').click(function(e) { $('#output').text(e.pageX + 'x' + e.pageY); });
Click
Example:
$('#target').click(function() { alert('hello, world!'); });
dbclick
raised when the user double clicks on an element.
Example:
$('#target').dbclick(function(){ alert('hello, world!'); });
Forms : blur, change, focus
blur
raised when a form element loses what’s known as focus. often used for validation.
Example:
$('#target').blur(function() { // retrieve the value using val var value = $('#target').val(); alert(value); })
change
raised whenever an element is modified.limited to
input
,textarea
andselect
elements only.Example:
$(function() { $('#parent').change(function() { var value = $('#parent').val(); $('#child').empty(); $('#child').append('<option>1 - ' + value + '</option>'); $('#child').append('<option>2 - ' + value + '</option>'); }) });
focus
the opposite of
blur
. raised when the user clicks, taps, or tabs into a particular control, typically because they want to change its value.Example:
<!-- sample HTML --> <div> <label for="phone">Phone</label> <input type="text" id="phone" /> <span id="phone-help"></span> </div> // sample JavaScript $('#phone').focus(function() { // Control has focus. Display help $('#phone-help').text('Please enter your phone number as all digits'); }).blur(function() { // Control lost focus. Clear help $('#phone-help').text(''); });
Mouse movement
mouseenter
,mouseleave
mouseenter
is raised whenever the user moves their mouse over an element.mouseleave
is raised when the user moves their mouse away from an element.Example:
<!-- sample HTML --> <div> <span id="target">Basic data</span> <span id="target-help"></span> </div> // sample JavaScript $('#target').mouseenter(function() { $('#target-help').text('More data'); }).mouseleave(function() { $('#target-help').text(''); });
hover
equivalent to both the
mouseenter
andmouseleave
events. The first parameterhover
accepts is formouseenter
, or when the hover begins, and the second parameter is formouseout
.Example:
$('#target').hover(function() { // mouseenter $('#target-help').text('More data'); }, function() { // mouseleave $('#target-help').text(''); });
Modifying elements
Replacing element HTML and text
val
for read the value, like to say retrieve the value of an input control, you can use
val()
var value = $('#some-input-control').val();
also, you can set the value. use
val(new-value)
Example: set a textbox to a blank value
// Empty a textbox $('#some-textbox').val('');
html
you have saw it in Module1.
Example:
// write text out to the screen // this will be displayed as // <strong>value</strong> // the text value will not be bolded $('#output').text('value');
text
Example:
// write text out to the screen // this will be displayed as value // with the word bolded $('#output').html('value');
Working with attribute and classes
attr
To retrieve the value of an attribute, simply call
attr(name)
.To change the value of an attribute, simply call
attr(name, newValue)
.addClass
andremoveClass
You have known it in Module1. Besides, one nice thing about
removeClass
is it will not throw an error if the class doesn’t exist.
Working with styles
css
To retrieve the value of a CSS property, call
css(property)
.To set a property, call
css(property, newValue)
Example:
// Retrieve an item's color var color = $('#target').css('color'); // Change an item's color to red $('#target').css('color', 'red');
To set multiple properties, create a JavaScript object with the property/value pairs, and then pass the object into the
css
function.Example:
var style = { color: 'red', backgroundColor: yellow }; $('#target').css(style);
Registering event handlers
Dynamic event handlers
on
,off
Both
on
andoff
share the same syntax:$('selector').on/off('events', 'selector (optional)', function)
Here,
events
: A space separated list of the events you wish to register, such as'click'
or'click mouseenter'
BTW, Obviously if you need to dynamically choose the event, or if you need multiple events for the same event handler, using
on
is your only choice.In additon,
on
offers one more feature, known as delegation.
Delegation
Registering an event handler using
delegate
, is similar toon
, with one major difference: New elements will automatically have the event handler applied.The
delegate
syntax:$(selector).delegate(selector, events, eventHandler)
Example:
<!-- sample HTML --> <button>Click</button> <div id="placeholder"></div> //JS $(function() { // document.ready (on load) // register a click event handler with all button elements, except new button //$('button').click(function() { alert('hello'); }); // new button will also be raised $(document).delegate('button', 'click', function() { alert('hello'); }); // create a new button $('#placeholder').html('<button>New button</button>'); });
With jQuery 1.7,
delegate
is superseded byon
.One important thing to note is the order of parameters for
on
anddelegate
.With
on
, you list the events first and the selector second. Withdelegate
, it’s selector followed by events.Example:
// Delegation (note the order of parameters) $(document).on('click', 'button', function() {alert('hello'); }); // Semantically the same as above // (note the order of parameters) $(document).delegate('button', 'click', function() { alert('hello'); });
Single execution
one
one
shares a similar syntax withon
, only there is no delegation option.The event only execute once.
Example:
<!-- sample HTML --> <button id="single">This only works once</button> <div id="output"></div> //JS $(function() { $('#single').one('click', function() { $('#output').text('You clicked on the button'); }); });
Triggering events
Raise the event programatically, like to click on a button to refresh data.
trigger
andtriggerHandler
allow you to provide the name of the event as a parameter.trigger
will execute for all elements in the collection,while
triggerHandler
only executes the handler for the first element.Example:
<!-- sample HTML --> <button type="button" id="first">First button</button> <button type="button" id="Second">Second button</button> <button type="button" id="trigger">trigger</button> <button type="button" id="trigger-handler">triggerHandler</button> //JS $(function() { $('button').click(function() { // display the id of the button alert(this.id); }); $('#trigger').click(function() { // Would alert every button's id // including the last two $('button').trigger('click'); }); // Would alert "first" $('#trigger-handler').click(function() { // Would alert "first" $('button').triggerHandler('click'); }); });
This is the first three parts of Module2 all about. More details.