0% found this document useful (0 votes)
8 views

JQuery Notes

jQuery is a fast and feature-rich JavaScript library that simplifies HTML document manipulation, event handling, and AJAX interactions. Created by John Resig in 2006, it has become popular due to its ease of use and cross-browser compatibility. The document covers jQuery's syntax, selectors, DOM manipulation, event handling, and form validation techniques.

Uploaded by

vyshnavshan34
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

JQuery Notes

jQuery is a fast and feature-rich JavaScript library that simplifies HTML document manipulation, event handling, and AJAX interactions. Created by John Resig in 2006, it has become popular due to its ease of use and cross-browser compatibility. The document covers jQuery's syntax, selectors, DOM manipulation, event handling, and form validation techniques.

Uploaded by

vyshnavshan34
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

jQuery Notes

Introduction to jQuery
Overview of jQuery
 What is jQuery?
o jQuery is a fast, small, and feature-rich JavaScript library.
o It simplifies tasks like HTML document traversal, event handling, animations,
and AJAX interactions.
o Motto: "Write less, do more."
History
 It was created by John Resig and was released at BarCamp NYC in January 2006.
 Became one of the most popular JavaScript libraries due to its simplicity and cross-
browser compatibility.
 It is currently maintained by a team of developers led by Timmy Willison
Features
 Simplified HTML document traversal and manipulation.
 Event handling and animation capabilities.
 AJAX support for seamless server interactions.
 Cross-browser compatibility.
 Extensibility via plugins.
Advantages
 Easy to use and learn.
 Reduces code complexity.
 Excellent community support.
 Enhances user experience with animations and dynamic content.
Setting up jQuery
Installation Methods
1. Using CDN (Content Delivery Network)
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
 Downloading and Including Locally
 Download from jQuery website.
 Include using:
<script src="path/to/jquery.min.js"></script>
Understanding the jQuery Syntax
Basic jQuery Syntax
The basic syntax of jQuery follows this pattern:
$(selector).action();
 $ → Represents jQuery.
 selector → Specifies the HTML element(s) to target.
 action() → Defines what happens to the selected elements.

Example:
The following example says: When a click event fires on a <p> element; hide the
current <p> element:
$(document).ready(function() {
$('p').click(function() {
$(this).hide();
});
});

Selecting Elements with jQuery


jQuery uses CSS-style selectors to find and manipulate elements.
Common jQuery Selectors
Selector Description Example

* Selects all elements $("*")

#id Selects an element by ID $("#myId")

.class Selects elements by class $(".myClass")

element Selects elements by tag $("p") (all <p> elements)

element1, element2 Selects multiple elements $("h1, p")

parent child Selects direct descendants $("div p")

parent > child Selects immediate children $("div > p")


Selector Description Example

prev + next Selects next sibling $("h1 + p")

prev ~ siblings Selects all siblings $("h1 ~ p")

Example

$(document).ready(function() {
$("p").css("color", "blue"); // Selects all <p> elements and changes text color
$(".highlight").css("background-color", "yellow"); // Selects elements with class 'highlight'
$("#mainTitle").css("font-size", "24px"); // Selects the element with ID 'mainTitle'
});
Using Basic Filters in jQuery
Filters allow you to refine selections and target specific elements.
3.1 Common jQuery Filters
Filter Description Example

:first Selects the first element $("p:first")

:last Selects the last element $("p:last")

:even Selects even-indexed elements $("tr:even")

:odd Selects odd-indexed elements $("tr:odd")

:eq(n) Selects the nth element (0-based index) $("li:eq(2)")

:gt(n) Selects elements greater than index n $("li:gt(1)")

:lt(n) Selects elements less than index n $("li:lt(3)")

:not(selector) Selects all except the specified element $("p:not(.exclude)")


Example: Using Filters
$(document).ready(function() {
$("p:first").css("font-weight", "bold"); // Makes first <p> bold
$("li:even").css("background-color", "#f2f2f2"); // Colors even <li> items
$("div:not(.skip)").css("border", "1px solid black"); // Adds border to divs except those
with class 'skip'
});
DOM Manipulation with jQuery
Introduction
The Document Object Model (DOM) represents the structure of a webpage as a tree of
elements. jQuery makes it easy to traverse, modify, and interact with these elements
efficiently.

1. Traversing the DOM with jQuery


1.1 Understanding DOM Traversal
DOM traversal in jQuery refers to navigating through elements in the document hierarchy.
jQuery provides several methods to move between elements.
1.2 Common Traversal Methods
Method Description

.parent() Selects the parent of an element

.children() Selects direct children of an element

.siblings() Selects all sibling elements

.find() Searches for descendants of an element

.next() Selects the next sibling

.prev() Selects the previous sibling


1.3 Example: Traversing the DOM
$(document).ready(function() {
$("#child").parent().css("border", "2px solid red"); // Selects parent
$("#parent").children().css("color", "blue"); // Selects children
$("#child").siblings().css("background-color", "lightgray"); // Selects siblings
});

2. Modifying HTML Content with jQuery


jQuery provides various methods to manipulate HTML content dynamically.
2.1 Changing Text and HTML
 .text(): Changes or retrieves text inside an element.
 .html(): Changes or retrieves inner HTML content.
Example: Modifying Text and HTML
$(document).ready(function() {
$("#changeText").click(function() {
$("#textElement").text("New Text Content");
});

$("#changeHtml").click(function() {
$("#htmlElement").html("<b>Bold HTML Content</b>");
});
});
2.2 Changing Attributes
 .attr(): Gets or sets attribute values.
Example: Changing Image Source
$(document).ready(function() {
$("#changeImage").click(function() {
$("#myImage").attr("src", "new-image.jpg");
});
});

3. Adding, Removing, and Modifying DOM Elements


3.1 Adding Elements
 .append(): Adds content inside an element at the end.
 .prepend(): Adds content inside an element at the beginning.
 .after(): Inserts content after an element.
 .before(): Inserts content before an element.
Example: Adding Elements
$(document).ready(function() {
$("#addItem").click(function() {
$("#list").append("<li>New Item</li>");
});
});
3.2 Removing Elements
 .remove(): Removes an element completely.
 .empty(): Clears the content of an element.
Example: Removing Elements
$(document).ready(function() {
$("#removeItem").click(function() {
$("#list li:last").remove();
});

$("#clearList").click(function() {
$("#list").empty();
});
});
3.3 Modifying CSS
 .css(): Changes CSS properties dynamically.
Example: Changing Background Color
$(document).ready(function() {
$("#changeColor").click(function() {
$("body").css("background-color", "lightblue");
});
});

4. Handling Events with jQuery


4.1 Common jQuery Events
Event Description

.click() Triggers when an element is clicked

.dblclick() Triggers on a double click

.hover() Triggers when hovering over an element


Event Description

.focus() Triggers when an input field gains focus

.blur() Triggers when an input field loses focus

.submit() Triggers when a form is submitted


4.2 Handling Click Events
Example: Click Event
$(document).ready(function() {
$("#clickMe").click(function() {
alert("Button clicked!");
});
});
4.3 Handling Hover Events
Example: Hover Effect
$(document).ready(function() {
$("#hoverBox").hover(function() {
$(this).css("background-color", "yellow");
}, function() {
$(this).css("background-color", "white");
});
});
4.4 Handling Form Events
 .focus(): Triggers when input is selected.
 .blur(): Triggers when input loses focus.
 .submit(): Triggers when a form is submitted.
Example: Form Validation on Blur
$(document).ready(function() {
$("#name").blur(function() {
if ($(this).val() === "") {
alert("Name cannot be empty");
}
});
});

Working with Forms and Form Validation


Forms are a crucial part of web applications, allowing users to submit data. jQuery simplifies
form handling and validation, ensuring a smooth user experience.
Handling Form Submissions
Form submission can be managed using jQuery’s event handlers. The most common methods
include:
 .submit() - To detect form submissions.
 .serialize() - Gathers form data and converts it into a query string.
 .ajax() - Sends form data asynchronously to the server.
Validating Forms
Validation ensures that users enter correct and complete data before submission. jQuery
provides methods to check form fields before sending the data.
Common approaches include:
 Checking input length
 Validating email formats
 Ensuring required fields are filled

Example
Basic Validation Using .val()
The .val() method retrieves or sets values of form inputs.

$(document).ready(function() {
$("#myForm").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
if (name === "") {
alert("Name field cannot be empty");
} else {
alert("Form submitted successfully!");
}
});
});
Checking for Email Format
Using regular expressions (RegEx) to check if an email is valid.
$(document).ready(function() {
$("#myForm").submit(function(event) {
event.preventDefault();
var email = $("#email").val();
var emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (!email.match(emailPattern)) {
alert("Invalid email address");
} else {
alert("Email is valid!");
}
});
});
Password Strength Validation
Checking for password length and complexity.
$(document).ready(function() {
$("#myForm").submit(function(event) {
event.preventDefault();
var password = $("#password").val();
if (password.length < 6) {
alert("Password must be at least 6 characters long");
} else {
alert("Password is strong!");
}
});
});
Using jQuery Plugins for Form Validation
For advanced validation, jQuery plugins like simplify the process. This plugin provides
built-in validation rules and easy customization.

Steps to Use jQuery Validation Plugin


1 Include the plugin in your project:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js">
</script>
2 Apply validation rules:

$(document).ready(function(){
$("#myForm").validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please enter your name",
email: "Enter a valid email address"
},
submitHandler: function(form) {
form.submit();
}
});
});
This automatically applies validation rules and displays error messages.
Implementing Custom Form Validation
Apart from using plugins, we can create our own custom validation functions using jQuery.
Example:
Custom Validation for Phone Number
Validating a 10-digit phone number.
Example: Custom Phone Validation

$(document).ready(function() {
$("#myForm").submit(function(event) {
event.preventDefault();
var phone = $("#phone").val();
var phonePattern = /^[0-9]{10}$/;
if (!phone.match(phonePattern)) {
alert("Invalid phone number. Must be 10 digits.");
} else {
alert("Phone number is valid!");
}
});
});
Summary
 jQuery simplifies JavaScript by providing easy-to-use methods for DOM
manipulation, event handling, and AJAX interactions.
 Effective for enhancing user interfaces and ensuring cross-browser compatibility.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy