Scripting LanguageUnit 913 min read
jQuery: Selectors, Effects, AJAX & UI Widgets
Unit 9 of Scripting Language covers jQuery’s core concepts—selectors, DOM manipulation, effects, AJAX, and UI widgets—with real-world examples from eSewa, Daraz, and Ncell, plus visual traces of operations like date picker integration and hide/show animations.
TAKEAWAYS:
- jQuery is a fast, lightweight JavaScript library that simplifies DOM manipulation, event handling, and AJAX calls using concise syntax.
- Selectors (e.g.,
$("p"),$("#id")) target elements like CSS, while effects (e.g.,.slideUp(),.fadeIn()) animate them. - AJAX in jQuery (
$.ajax(),$.get()) enables dynamic data loading without page reloads (e.g., Daraz’s live order tracking). - UI widgets (e.g., date pickers, dialogs) enhance interactivity (e.g., eSewa’s payment deadlines).
- jQuery vs. Vanilla JS: jQuery reduces boilerplate code (e.g.,
$("#btn").click()vs.document.getElementById("btn").addEventListener("click", ...)). - Exam focus: Code snippets (e.g., hide/show divs, date pickers), selector types, and AJAX properties/methods.
1. What is jQuery?
jQuery is a fast, cross-browser JavaScript library designed to simplify:
- DOM manipulation (e.g., changing HTML/CSS dynamically).
- Event handling (e.g., clicks, keypresses).
- AJAX (asynchronous data fetching).
- Animations and effects (e.g., fade, slide).
Why Use jQuery?
| Feature | Vanilla JavaScript | jQuery |
|---|---|---|
| DOM Selection | document.querySelector("#id") |
$("#id") |
| Event Binding | element.addEventListener("click", ...) |
$("#id").click(...) |
| AJAX | XMLHttpRequest (verbose) |
$.ajax() (concise) |
| Cross-Browser | Manual fixes for IE, Firefox, etc. | Built-in compatibility |
Example: Without jQuery, hiding a <div> requires 5+ lines. With jQuery:
$("#myDiv").hide(); // Instant!
2. jQuery Selectors
Selectors target HTML elements using CSS-like syntax. Common types:
A. Basic Selectors
Example: Select all <li> items in an unordered list:
$("ul li").css("color", "red"); // Turns all list items red
B. Hierarchy Selectors
| Selector | Example | Description |
|---|---|---|
| Ancestor | $("div p") |
<p> inside <div> |
| Child | $("ul > li") |
Direct <li> children of <ul> |
| Next sibling | $("h1 + p") |
<p> immediately after <h1> |
Real-World Use: Daraz’s product filters
Daraz uses jQuery selectors to dynamically update product lists when users click filters (e.g., $(".filter-active").siblings().hide()).
3. jQuery Effects
Effects animate elements without Flash. Key methods:
A. Hide/Show Effects
flowchart LR
A["Start"] --> B["$(\"#div\").show()"] --> C["Div appears"]
C --> D["$(\"#div\").hide()"] --> E["Div disappears"]
E --> F["$(\"#div\").toggle()"] -->|"If visible"| G["Div hides"]
F -->|"If hidden"| H["Div appears"]Example: Toggle a "Read More" section:
$("#readMore").click(function() {
$("#hiddenText").slideToggle("slow");
});
B. Other Effects
| Method | Example | Effect |
|---|---|---|
.fadeIn() |
$("#box").fadeIn(1000); |
Gradually appears |
.slideUp() |
$("#panel").slideUp(); |
Slides upward and hides |
.animate() |
$("#box").animate({left: "250px"}); |
Custom CSS animations |
Real-World Use: eSewa’s payment success page After a transaction, eSewa fades in a success message:
$(".success-message").fadeIn(500);
4. jQuery AJAX
AJAX (Asynchronous JavaScript and XML) fetches data without reloading the page.
A. $.ajax() Method
sequenceDiagram
participant User
participant jQuery
participant Server
User->>jQuery: $.ajax({url: "api/data", success: callback})
jQuery->>Server: GET /api/data
Server-->>jQuery: {data: "..."}
jQuery->>User: callback(data)Example: Load user data from an API:
$.ajax({
url: "https://api.example.com/user",
method: "GET",
success: function(data) {
$("#userName").text(data.name);
},
error: function() {
alert("Error loading data!");
}
});
B. Shorthand Methods
| Method | Example | Use Case |
|---|---|---|
$.get() |
$.get("data.txt", showData) |
Fetch text/data |
$.post() |
$.post("submit.php", {name: "A"}) |
Send form data to server |
$.load() |
$("#result").load("update.html") |
Load HTML into an element |
Real-World Use: Ncell’s balance check
Ncell’s website uses $.get() to fetch balance without refreshing:
$.get("check_balance.php", {userId: 123}, function(data) {
$("#balance").text("Rs. " + data.balance);
});
5. jQuery UI Widgets
jQuery UI provides pre-built interactive widgets (requires jquery-ui.js).
A. Datepicker
flowchart LR
A["Input field"] --> B["$(\"#datepicker\").datepicker()]"]
B --> C["Calendar popup appears"]
C --> D["User selects date"]
D --> E["Input field updates"]Example: Add a datepicker to an input:
<input type="text" id="datepicker">
<script>
$(function() {
$("#datepicker").datepicker();
});
</script>
Real-World Use: NTC’s ticket booking NTC’s website uses the datepicker for selecting travel dates:
$("#departureDate").datepicker({ minDate: "+1d" }); // Disable past dates
B. Dialog Box
$("#confirm").click(function() {
$("#dialog").dialog({
title: "Confirm Order",
buttons: {
"Yes": function() { $(this).dialog("close"); orderSubmit(); },
"No": function() { $(this).dialog("close"); }
}
});
});
Real-World Use: Pathao’s order confirmation Pathao shows a dialog before finalizing a ride:
$("#confirmRide").dialog({
modal: true,
buttons: { "Confirm": confirmRide }
});
6. jQuery vs. Vanilla JavaScript
| Task | jQuery | Vanilla JavaScript |
|---|---|---|
| Select element | $("#id") |
document.getElementById("id") |
| Add click event | $("#btn").click(...) |
element.addEventListener("click", ...) |
| AJAX request | $.ajax({...}) |
fetch() or XMLHttpRequest |
| Hide element | $("#div").hide() |
element.style.display = "none" |
| Animation | $("#box").fadeOut() |
CSS @keyframes or requestAnimationFrame |
Why jQuery?
- Less code: 1 line vs. 5+ lines for DOM tasks.
- Cross-browser: Works on IE, Firefox, Chrome without fixes.
- Effects/AJAX: Built-in methods for animations and async calls.
7. Common Exam Questions & Answers
Q1: Differentiate jQuery from JavaScript.
Answer:
- JavaScript is a full-fledged programming language for web interactivity.
- jQuery is a library that simplifies JS tasks (e.g., DOM manipulation, AJAX) with shorter syntax.
- Example:
// Vanilla JS document.getElementById("btn").addEventListener("click", function() { document.getElementById("content").style.display = "none"; }); // jQuery $("#btn").click(function() { $("#content").hide(); });
Q2: Write jQuery code to hide/show a div.
Answer:
$("#toggleBtn").click(function() {
$("#myDiv").slideToggle("fast");
});
Trace:
| Step | Action | State After Step |
|---|---|---|
| 1 | User clicks #toggleBtn |
$("#myDiv").slideToggle() triggered |
| 2 | If #myDiv is visible |
#myDiv slides up and hides |
| 3 | If #myDiv is hidden |
#myDiv slides down and appears |
Q3: Explain $.ajax() properties.
Answer:
| Property | Description | Example |
|---|---|---|
url |
Target URL | url: "api/data" |
method |
HTTP method (GET, POST) |
method: "POST" |
data |
Data to send | data: {name: "Alice"} |
success |
Callback on success | success: function(data) {...} |
error |
Callback on failure | error: function() {...} |
Example:
$.ajax({
url: "save_order.php",
method: "POST",
data: {orderId: 123, status: "shipped"},
success: function() { alert("Order updated!"); }
});
## In the Real World
eSewa (Payment Deadlines)
- Idea Used: jQuery effects (
fadeIn(),hide()). - How: After a payment, eSewa fades in a success message and hides the payment form:
$(".payment-form").fadeOut(500, function() { $(".success-message").fadeIn(500); });
- Idea Used: jQuery effects (
Daraz (Live Order Tracking)
- Idea Used: jQuery AJAX (
$.get()). - How: Daraz updates order status without refreshing:
function checkOrder() { $.get("track_order.php", {orderId: 1001}, function(data) { $("#status").text(data.status); }); } setInterval(checkOrder, 5000); // Check every 5 seconds
- Idea Used: jQuery AJAX (
Ncell (Balance Check)
- Idea Used: jQuery selectors and AJAX.
- How: Ncell’s website loads balance dynamically:
$("#checkBalance").click(function() { $.post("balance.php", {userId: 456}, function(data) { $("#balance").text("Rs. " + data.balance); }); });
NTC (Ticket Booking Dates)
- Idea Used: jQuery UI Datepicker.
- How: Users select travel dates via a calendar popup:
$("#departureDate").datepicker({ minDate: "+1d", // Disable past dates dateFormat: "yy-mm-dd" });
## Exam Tip
- Code Snippets: Always write complete, runnable jQuery code in exams (e.g., hide/show divs, date pickers).
- Selector Types: Memorize basic (
#id,.class), hierarchy (parent > child), and attribute ([type="text"]) selectors. - AJAX Properties: Know
url,method,data,success, anderrorfor$.ajax(). - Real-World Tie-Ins: Relate examples to eSewa (effects), Daraz (AJAX), or NTC (datepicker).
- jQuery vs. JS: Compare syntax length and cross-browser support.
## Practice Questions
- Write jQuery code to:
- Toggle the visibility of a
<div>with IDcontentwhen a button is clicked. - Load data from
api/usersand display usernames in a<ul>.
- Toggle the visibility of a
- Explain the difference between
$("div p")and$("div > p"). - How would you use jQuery UI’s dialog widget to confirm a form submission?
- Trace the execution of
$("#box").animate({left: "100px"}, 1000)step-by-step.
## Key Formulas/Shortcuts
| Task | jQuery Shortcut |
|---|---|
| Select by ID | $("#id") |
| Select by class | $(".class") |
| Hide element | $("#id").hide() |
| Show element | $("#id").show() |
| Toggle visibility | $("#id").toggle() |
| AJAX GET request | $.get("url", callback) |
| AJAX POST request | $.post("url", data, callback) |
| Add datepicker | $("#id").datepicker() |
## Common Mistakes to Avoid
- Forgetting
$: Always prefix selectors with$(e.g.,$("#id"), not("#id")). - Incorrect Selectors:
$("div.p")selects<div>with classp, not<p>inside<div>(use$("div p")). - Missing Callbacks: In AJAX, omit
success/errorhandlers to break functionality. - Not Including jQuery UI: Widgets like datepicker require
jquery-ui.jsand CSS. - Overusing jQuery: For complex apps, modern JS (e.g.,
fetch(),querySelector) may be preferred.
Based on the TU BCA syllabus for Scripting Language (CACS254), unit 9.
Discussion
Loading…