Jquery
Selecting Elements with jQuery
JavaScript is most commonly used to get or modify the content or value of the HTML elements on the page, as well as to apply some effects like show, hide, animations etc. But, before you can perform any action you need to find or select the target HTML element.
Selecting the elements through a typical JavaScript approach could be very painful, but the jQuery works like a magic here. The ability of making the DOM elements selection simple and easy is one of the most powerful feature of the jQuery.
Tip: The jQuery supports almost all the selectors defined in the latest CSS3 specifications, as well as it has its own custom selectors. These custom selectors greatly enhance the capabilities selecting the HTML elements on a page.
In the following sections, you will see some of the common ways of selecting the elements on a page and do something with them using the jQuery.
Selecting Elements by ID
You can use the ID selector to select a single element with the unique ID on the page.
For example, the following jQuery code will select and highlight an element having the ID attribute id="mark"
, when the document is ready to be manipulated.
Example
In the example above, the $(document).ready()
is an event that is used to manipulate a page safely with the jQuery. Code included inside this event will only run once the page DOM is ready. We'll learn more about the events in next chapter.
Selecting Elements by Class Name
The class selector can be used to select the elements with a specific class.
For example, the following jQuery code will select and highlight the elements having the class attribute class="mark"
, when the document is ready.
Example
Selecting Elements by Name
The element selector can be used to select elements based on the element name.
For example, the following jQuery code will select and highlight all the paragraph i.e. the <p>
elements of the document when it is ready.
Example
Selecting Elements by Attribute
You can use the attribute selector to select an element by one of its HTML attributes, such as a link's target
attribute or an input's type
attribute, etc.
For example, the following jQuery code will select and highlight all the text inputs i.e. <input>
elements with the type="text"
, when the document is ready.
Example
Selecting Elements by Compound CSS Selector
You can also combine the CSS selectors to make your selection even more precise.
For instance, you can combine the class selector with an element selector to find the elements in a document that has certain type and class.
Example
jQuery Custom Selector
In addition to the CSS defined selectors, jQuery provides its own custom selector to further enhancing the capabilities of selecting elements on a page.
Example
Example
In the above example we've performed a simple jQuery operation by changing the color of the heading i.e. the <h1>
element using the jQuery element selector and css()
method when the document is ready which is known as document ready event. We'll learn about jQuery selectors, events and methods in upcoming chapters.
jQuery Events
In this tutorial you will learn how to handle events with jQuery.
What are Events
Events are often triggered by the user's interaction with the web page, such as when a link or button is clicked, text is entered into an input box or textarea, selection is made in a select box, key is pressed on the keyboard, the mouse pointer is moved etc. In some cases, the Browser itself can trigger the events, such as the page load and unload events.
jQuery enhances the basic event-handling mechanisms by offering the events methods for most native browser events, some of these methods are ready()
, click()
, keypress()
, focus()
, blur()
, change()
, etc. For example, to execute some JavaScript code when the DOM is ready, you can use the jQuery ready()
method, like this:
Example
Note: The $(document).ready()
is an event that is used to manipulate a page safely with the jQuery. Code included inside this event will only run once the page DOM is ready i.e. when the document is ready to be manipulated.
In general, the events can be categorized into four main groups — mouse events, keyboard events, form events and document/window events. The following section will give you the brief overview of all these events as well as related jQuery methods one by one.
Mouse Events
A mouse event is fired when the user click some element, move the mouse pointer etc. Here're some commonly used jQuery methods to handle the mouse events.
The click()
Method
click()
MethodThe jQuery click()
method attach an event handler function to the selected elements for "click" event. The attached function is executed when the user clicks on that element. The following example will hide the <p>
elements on a page when they are clicked.
Example
Note: The this
keyword inside the jQuery event handler function is a reference to the element where the event is currently being delivered.
The dblclick()
Method
dblclick()
MethodThe jQuery dblclick()
method attach an event handler function to the selected elements for "dblclick" event. The attached function is executed when the user double-clicks on that element. The following example will hide the <p>
elements when they are double-clicked.
Example
The hover()
Method
hover()
MethodThe jQuery hover()
method attach one or two event handler functions to the selected elements that is executed when the mouse pointer enters and leaves the elements. The first function is executed when the user place the mouse pointer over an element, whereas the second function is executed when the user removes the mouse pointer from that element.
The following example will highlight <p>
elements when you place the cursor on it, the highlighting will be removed when you remove the cursor.
Example
Tip: You can consider the hover()
method is a combination of the jQuery mouseenter()
and mouseleave()
methods.
The mouseenter()
Method
mouseenter()
MethodThe jQuery mouseenter()
method attach an event handler function to the selected elements that is executed when the mouse enters an element. The following example will add the class highlight to the <p>
element when you place the cursor on it.
Example
The mouseleave()
Method
mouseleave()
MethodThe jQuery mouseleave()
method attach an event handler function to the selected elements that is executed when the mouse leaves an element. The following example will remove the class highlight from the <p>
element when you remove the cursor from it.
Example
For more mouse event methods, please check out the jQuery Events Reference »
Keyboard Events
A keyboard event is fired when the user press or release a key on the keyboard. Here're some commonly used jQuery methods to handle the keyboard events.
The keypress()
Method
keypress()
MethodThe jQuery keypress()
method attach an event handler function to the selected elements (typically form controls) that is executed when the browser receives keyboard input from the user. The following example will display a message when the kypress event is fired and how many times it is fired when you press the key on the keyboard.
Example
Note: The keypress event is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, Backspace or Delete, Arrow keys etc. trigger keydown events but not keypress events.
The keydown()
Method
keydown()
MethodThe jQuery keydown()
method attach an event handler function to the selected elements (typically form controls) that is executed when the user first presses a key on the keyboard. The following example will display a message when the keydown event is fired and how many times it is fired when you press the key on the keyboard.
Example
The keyup()
Method
keyup()
MethodThe jQuery keyup()
method attach an event handler function to the selected elements (typically form controls) that is executed when the user releases a key on the keyboard. The following example will display a message when the keyup event is fired and how many times it is fired when you press and release a key on the keyboard.
Example
Tip: The keyboard events can be attached to any element, but the event is only sent to the element that has the focus. That's why the keyboard events generally attached to the form controls such as text input box or textarea.
Form Events
A form event is fired when a form control receive or loses focus or when the user modify a form control value such as by typing text in a text input, select any option in a select box etc. Here're some commonly used jQuery methods to handle the form events.
The change()
Method
change()
MethodThe jQuery change()
method attach an event handler function to the <input>
, <textarea>
and <select>
elements that is executed when its value changes. The following example will display an alert message when you select any option in dropdown select box.
Example
Note: For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the text input and textarea the event is fired after the element loses focus.
The focus()
Method
focus()
MethodThe jQuery focus()
method attach an event handler function to the selected elements (typically form controls and links) that is executed when it gains focus. The following example will display a message when the text input receive focus.
Example
The blur()
Method
blur()
MethodThe jQuery blur()
method attach an event handler function to the form elements such as <input>
, <textarea>
, <select>
that is executed when it loses focus. The following example will display a message when the text input loses focus.
Example
The submit()
Method
submit()
MethodThe jQuery submit()
method attach an event handler function to the <form>
elements that is executed when the user is attempting to submit a form. The following example will display a message depending on the value entered when you try to submit the form.
Example
Tip: A form can be submitted either by clicking a submit button, or by pressing Enter when certain form elements have focus.
Document/Window Events
Events are also triggered in a situation when the page DOM (Document Object Model) is ready or when the user resize or scrolls the browser window, etc. Here're some commonly used jQuery methods to handle such kind of events.
The ready()
Method
ready()
MethodThe jQuery ready()
method specify a function to execute when the DOM is fully loaded.
The following example will replace the paragraphs text as soon as the DOM hierarchy has been fully constructed and ready to be manipulated.
Example
The resize()
Method
resize()
MethodThe jQuery resize()
method attach an event handler function to the window element that is executed when the size of the browser window changes.
The following example will display the current width and height of the browser window when you try to resize it by dragging its corners.
Example
The scroll()
Method
scroll()
MethodThe jQuery scroll()
method attach an event handler function to the window or scrollable iframes and elements that is executed whenever the element's scroll position changes.
The following example will display a message when you scroll the browser window.
Example
jQuery Show and Hide Effects
In this tutorial you will learn how to show hide HTML elements using jQuery.
jQuery show()
and hide()
Methods
show()
and hide()
MethodsYou can show and hide HTML elements using the jQuery show()
and hide()
methods.
The hide()
method simply sets the inline style display: none
for the selected elements. Conversely, the show()
method restores the display properties of the matched set of elements to whatever they initially were—typically block, inline, or inline-block—before the inline style display: none
was applied to them. Here's is an example.
Example
You can optionally specify the duration (also referred as speed) parameter for making the jQuery show hide effect animated over a specified period of time.
Durations can be specified either using one of the predefined string 'slow'
or 'fast'
, or in a number of milliseconds, for greater precision; higher values indicate slower animations.
Example
Note: The speed or duration string 'fast'
indicates the durations of 200 milliseconds, while the string 'slow'
indicates the durations of 600 milliseconds.
You can also specify a callback function to be executed after the show()
or hide()
method completes. We'll learn more about the callback function in upcoming chapters.
Example
jQuery toggle()
Method
toggle()
MethodThe jQuery toggle()
method show or hide the elements in such a way that if the element is initially displayed, it will be hidden; if hidden, it will be displayed (i.e. toggles the visibility).
Example
Similarly, you can specify the duration parameter for the toggle()
method to make it animated like the show()
and hide()
methods.
Example
Similarly, you can also specify a callback function for the toggle()
method.
Example
jQuery Fading Effects
In this tutorial you will learn how to fade in and out elements using jQuery.
jQuery fadeIn()
and fadeOut()
Methods
fadeIn()
and fadeOut()
MethodsYou can use the jQuery fadeIn()
and fadeOut()
methods to display or hide the HTML elements by gradually increasing or decreasing their opacity.
Example
Like other jQuery effects methods, you can optionally specify the duration or speed parameter for the fadeIn()
and fadeOut()
methods to control how long the fading animation will run. Durations can be specified either using one of the predefined string 'slow'
or 'fast'
, or in a number of milliseconds; higher values indicate slower animations.
Example
Note: The effect of fadeIn()
/fadeOut()
method looks similar to show()
/hide()
, but unlike show()
/hide()
method the fadeIn()
/fadeOut()
method only animates the opacity of the target elements and does not animates their dimensions.
You can also specify a callback function to be executed after the fadeIn()
or fadeOut()
method completes. We'll learn more about the callback function in upcoming chapters.
Example
jQuery fadeToggle()
Method
fadeToggle()
MethodThe jQuery fadeToggle()
method display or hide the selected elements by animating their opacity in such a way that if the element is initially displayed, it will be fade out; if hidden, it will be fade in (i.e. toggles the fading effect).
Example
Similarly, you can specify the duration parameter for the fadeToggle()
method like fadeIn()
/fadeOut()
method to control the duration or speed of the fade toggle animation.
Example
Similarly, you can also specify a callback function for the fadeToggle()
method.
Example
jQuery fadeTo()
Method
fadeTo()
MethodThe jQuery fadeTo()
method is similar to the .fadeIn()
method, but unlike .fadeIn()
the fadeTo()
method lets you fade in the elements to a certain opacity level.$(selector).fadeTo(speed, opacity, callback);
The required opacity parameter specifies the final opacity of the target elements that can be a number between 0 and 1. The duration or speed parameter is also required for this method that specifies the duration of the fade to animation.
Example
jQuery Sliding Effects
In this tutorial you will learn how to create slide motion effect using jQuery.
jQuery slideUp()
and slideDown()
Methods
slideUp()
and slideDown()
MethodsThe jQuery slideUp()
and slideDown()
methods is used to hide or show the HTML elements by gradually decreasing or increasing their height (i.e. by sliding them up or down).
Example
Like other jQuery effects methods, you can optionally specify the duration or speed parameter for the slideUp()
and slideDown()
methods to control how long the slide animation will run. Durations can be specified either using one of the predefined string 'slow'
or 'fast'
, or in a number of milliseconds; higher values indicate slower animations.
Example
You can also specify a callback function to be executed after the slideUp()
or slideDown()
method completes. We'll learn more about the callback function in upcoming chapters.
Example
jQuery slideToggle()
Method
slideToggle()
MethodThe jQuery slideToggle()
method show or hide the selected elements by animating their height in such a way that if the element is initially displayed, it will be slide up; if hidden, it will be slide down i.e. toggles between the slideUp()
and slideDown()
methods.
Example
Similarly, you can specify the duration parameter for the slideToggle()
method like slideUp()
and slideDown()
methods to control the speed of the slide toggle animation.
Example
Similarly, you can also specify a callback function for the slideToggle()
method.
Example
jQuery Animation Effects
In this tutorial you will learn how to animate CSS properties using jQuery.
jQuery animate()
Method
animate()
MethodThe jQuery animate()
method is used to create custom animations. The animate()
method is typically used to animate numeric CSS properties, for example, width
, height
, margin
, padding
, opacity
, top
, left
, etc. but the non-numeric properties such as color
or background-color
cannot be animated using the basic jQuery functionality.
Note: Not all CSS properties are animatable. In general, any CSS property that accepts values that are numbers, lengths, percentages, or colors is animatable. However, the color animation is not support by the core jQuery library. To manipulate and animate the color use the jQuery color plugin.
Syntax
The basic syntax of the jQuery animate()
method can be given with:$(selector).animate({ properties }, duration, callback);
The parameters of the animate()
method have the following meanings:
The required properties parameter defines the CSS properties to be animated.
The optional duration parameter specifies how long the animation will run. Durations can be specified either using one of the predefined string
'slow'
or'fast'
, or in a number of milliseconds; higher values indicate slower animations.The optional callback parameter is a function to call once the animation is complete.
Here's a simple example of the jQuery animate()
method that animates an image from its original position to the right by 300 pixels on click of the button.
Example
Note: All HTML elements have static position by default. Since the static element cannot be moved, so you must set the CSS position
property for the element to relative
, fixed
, or absolute
to manipulate or animate its position.
Animate Multiple Properties At Once
You can also animate multiple properties of an element together at the same time using the animate()
method. All the properties animated simultaneously without any delay.
Example
Note: The CSS properties names must be camel-cased when using with the animate()
method, e.g. if you want to animate the font size you need to write 'fontSize'
rather than '
font-size
'
. Similarly, write 'marginLeft'
instead of '
margin-left
'
, 'borderWidth'
instead of '
border-width
'
, and so on.
Tip: You must set the border-style
property for the element before animating its border-width
property. An element must have borders before you can animate the border width, because the default value of the border-style
property is none
.
Animate Multiple Properties One by One or Queued Animations
You can also animate the multiple properties of an element one by one individually in a queue using the jQuery's chaining feature. We'll learn more about chaining in next chapter.
The following example demonstrates a jQuery queued or chained animation, where each animation will start once the previous animation on the element has completed.
Example
Animate Properties with Relative Values
You can also define the relative values for the animated properties. If a value is specified with a leading +=
or -=
prefix, then the target value is calculated by adding or subtracting the given number from the current value of the property.
Example
Animate Properties with Pre-defined Values
In addition to the numeric values, each property can take the strings 'show'
, 'hide'
, and 'toggle'
. It will be very helpful in a situation when you simply want to animate the property from its current value to the initial value and vice versa.
Example
jQuery Chaining
In this tutorial you will learn how chain multiple methods in jQuery.
jQuery Method Chaining
The jQuery provides another robust feature called method chaining that allows us to perform multiple action on the same set of elements, all within a single line of code.
This is possible because most of the jQuery methods return a jQuery object that can be further used to call another method. Here's an example.
Example
The above example demonstrate the chaining of three animate()
method. When a user click the trigger button, it expands the <p>
to 100% width. Once the width
change is complete the font-size
is start animating and after its completion, the border
animation will begin.
Tip: The method chaining not only helps you to keep your jQuery code concise, but it also can improve your script's performance since browser doesn't have to find the same elements multiple times to do something with them.
You can also break a single line of code into multiple lines for greater readability. For example, the sequence of methods in the above example could also be written as:
Example
Some jQuery methods doesn't return the jQuery object. In general, setters i.e. methods that assign some value on a selection return a jQuery object, that allows you to continue calling jQuery methods on your selection. Whereas, getters return the requested value, so you can't continue to call jQuery methods on the value returned by the getter.
A typical example of this scenario is the html()
method. If no parameters are passed to it, the HTML contents of the selected element is returned instead of a jQuery object.
Example
jQuery Callback
In this tutorial you will learn how define a callback function for the jQuery effect.
jQuery Callback Functions
JavaScript statements are executed line by line. But, since jQuery effect takes some time to finish the next line code may execute while the previous effect is still running. To prevent this from happening jQuery provides a callback function for each effect method.
A callback function is a function that is executed once the effect is complete. The callback function is passed as an argument to the effect methods and they typically appear as the last argument of the method. For example, the basic syntax of the jQuery slideToggle()
effect method with a callback function can be given with:$(selector).slideToggle(duration, callback);
Consider the following example in which we've placed the slideToggle()
and alert()
statements next to each other. If you try this code the alert will be displayed immediately once you click the trigger button without waiting for slide toggle effect to complete.
Example
And, here's the modified version of the pevious example in which we've placed the alert()
statement inside a callback function for the slideToggle()
method. If you try this code the alert message will be displayed once the slide toggle effect has completed.
Example
Similarly, you can define the callback functions for the other jQuery effect methods, like show()
, hide()
, fadeIn()
, fadeOut()
, animate()
, etc.
Note: If the effect method is applied to multiple elements, then the callback function is executed once for each selected element, not once for all.
Example
If you try the above example code, it will display the same alert message two times once per <h1>
and <p>
element, upon clicking the trigger button.
Last updated