CSC318 Web Technology

Web TechnologyUnit 69 min read

jQuery Selectors, Animations & Chaining: Syntax, Methods & Real-World Effects

Unit 6 of Web Technology covers jQuery’s core selectors (ID, class, attribute), animation methods (animate(), slideUp(), fadeOut()), callback functions, and chaining to create dynamic web interactions—with syntax, examples, and real-world applications like eSewa’s loading spinners and Pathao’s route transitions.

TAKEAWAYS:

  • jQuery selectors (#id, .class, [attr]) target HTML elements like CSS but enable dynamic manipulation via JavaScript.
  • The animate() method moves/resizes elements smoothly by specifying CSS properties (e.g., left, opacity) and duration.
  • Chaining (e.g., $("#btn").click().hide()) executes multiple jQuery methods sequentially on the same element.
  • Callbacks (e.g., .animate({...}, 1000, function(){...})) trigger code after an animation completes.
  • Real-world uses: eSewa’s transaction spinners (fadeIn/Out), Pathao’s driver location updates (animate()), and Khalti’s form validations (chaining).
  • Performance tip: Chain methods to reduce DOM queries; use stop() to halt animations mid-execution.

1. What is jQuery? Why Use It?

jQuery is a fast, lightweight JavaScript library designed to simplify HTML DOM traversal, event handling, animations, and AJAX. It abstracts cross-browser inconsistencies (e.g., IE vs. Chrome) and provides concise syntax for common tasks.

Key Advantages Over Vanilla JS

Feature jQuery Vanilla JavaScript
Syntax Short (e.g., $("#id")) Verbose (e.g., document.getElementById())
Browser Support Handles quirks automatically Requires polyfills for older browsers
Animations Built-in (e.g., fadeOut()) Manual CSS transitions or libraries
Chaining Native support Manual method calls
Performance Optimized for DOM operations Slower for repeated queries

2. jQuery Selectors: Targeting Elements

Selectors in jQuery work like CSS selectors but enable dynamic actions. Common types:

A. Basic Selectors

#id (by ID).class (by class)element (by tag)* (all elements)[attribute] (by attribute)jQuery Selectors
Hierarchy of jQuery basic selectors (top-down)
  • #id: Targets a single element by its id (e.g., $("#header")).
  • .class: Selects all elements with a class (e.g., $(".btn")).
  • element: Selects by tag (e.g., $("p") for all <p> tags).
  • [attribute]: Filters by attribute (e.g., $("input[type='text']")).

B. Hierarchy Selectors

#menu > liParent > Child (direct child)ul liParent Child (descendant)div:has(p)Parent :has(Child) (modern jQuery 3.6+)Hierarchy Selectors
Hierarchy selector relationships (jQuery 3.6+)
  • >: Direct child (e.g., $("#nav > ul")).
  • Space: Descendant (e.g., $("div p")).
  • :has(): jQuery 3.6+ (e.g., $("form:has(input.error)")).

Worked Example: eSewa’s Loading Spinner

When you click "Pay," eSewa shows a spinner. Here’s how jQuery selects and animates it:

<button id="payBtn">Pay Rs. 1000</button>
<div id="spinner" class="hidden">Loading...</div>

```figure
{"type":"timeline","events":[{"date":"Step 1","label":"Selector: `$('.spinner')`"},{"date":"Step 2","label":"Animation: `.fadeIn(1000)`"},{"date":"Step 3","label":"Callback: `.promise().done(function(){ ... })`"},{"date":"Result","label":"Smooth spinner effect"}],"caption":"Chaining workflow for eSewa’s loading animation"}
<script> $("#payBtn").click(function() { $("#spinner").removeClass("hidden").fadeIn(500); // Simulate payment processing setTimeout(() => { $("#spinner").fadeOut(500); }, 2000); }); </script>

3. jQuery Animation Methods

jQuery provides pre-built animations and the flexible animate() method.

A. Pre-Built Animations

Method Effect Example
show() Displays hidden elements $("#box").show(1000)
hide() Hides elements $("#box").hide()
toggle() Swaps visibility $("#box").toggle()
fadeIn() Fades in $("#box").fadeIn(1500)
fadeOut() Fades out $("#box").fadeOut()
slideUp() Slides up $("#panel").slideUp()
slideDown() Slides down $("#panel").slideDown()
toggletoggletoggleshow()hide()toggle()fadeIn()fadeOut()slideUp()slideDown()
jQuery pre-built animation relationships (toggle pairs)

B. Custom Animation with animate()

Syntax:

$("selector").animate(
  { properties: "values" },  // e.g., { left: "300px", opacity: 0.5 }
  duration,                  // e.g., 1000 (ms)
  easing,                    // e.g., "swing" (default)
  callback                  // function after animation
);

Worked Example: Pathao’s Driver Location Update Pathao updates a driver’s location on a map using animate() to move a marker smoothly:

<div id="driverMarker" style="position: absolute; left: 0; top: 0; width: 20px; height: 20px; background: red;"></div>

<script>
  let leftPos = 0;
  setInterval(() => {
    leftPos += 5;
    $("#driverMarker").animate(
      { left: leftPos + "px" },
      500,
      "linear",
      () => { if (leftPos > 500) leftPos = 0; }
    );
  }, 1000);
</script>

4. Chaining and Callbacks

A. Chaining

Combine multiple jQuery methods in a single line:

$("#btn")
  .css("color", "red")
  .text("Clicked!")
  .fadeOut(1000)
  .promise()
  .done(() => console.log("Animation done"));

Why chain?

  • Reduces DOM queries (faster).
  • Improves readability.

B. Callbacks

Execute code after an animation completes:

$("#box").animate({ width: "200px" }, 1000, function() {
  $(this).text("Animation complete!");
});

Worked Example: Daraz’s Order Confirmation When you click "Place Order," Daraz:

  1. Animates a loading spinner.
  2. On success, hides the spinner and shows a confirmation message.
$("#placeOrderBtn").click(function() {
  $("#spinner").fadeIn(500, function() {
    // Simulate API call
    setTimeout(() => {
      $("#spinner").fadeOut(500, function() {
        $("#confirmation").slideDown();
      });
    }, 1500);
  });
});

5. Real-World Applications

Company/Product jQuery Feature Used How It’s Implemented
eSewa fadeIn()/fadeOut() Transaction spinners during payment processing.
Pathao animate() Smooth driver location updates on the map.
Khalti Chaining + show()/hide() Form validation feedback (e.g., error messages).
NTC Website slideDown()/slideUp() FAQ accordion sections.
YouTube (Global) animate() + css() Like button animations.

6. Common Pitfalls and Fixes

Issue Cause Solution
Animation doesn’t start Incorrect selector Use $("body").on("click", "#btn", ...) for dynamic elements.
Elements jump during animation position: absolute missing Add position: absolute to animated elements.
Callback not firing Missing function(){...} Always include a callback for async tasks.
Performance lag Too many animations Use requestAnimationFrame for complex animations.

Exam Tip

  1. Syntax is key: Memorize the exact syntax for animate(), selectors, and chaining. For example:
    // Correct:
    $("#mydiv").animate({ left: "+=300px" }, 1000);
    // Wrong:
    $("#mydiv").animate(left: "300px"); // Missing {}
    
  2. Draw diagrams: In exams, sketch a mermaid sequence diagram for animation flows (e.g., click → animate → callback).
  3. Real-world tie-ins: Always relate answers to apps like eSewa or Pathao. For example:

    "Like Pathao’s driver tracker, we use animate() to update the marker’s position by incrementally changing its left CSS property."

  4. Practice chaining: Examiners love questions on chaining. Example:
    $("#btn").click().addClass("active").text("Processing...");
    
  5. Avoid stop() in basic questions: Unless asked, assume animations run to completion.

Based on the TU BSc CSIT syllabus for Web Technology (CSC318), unit 6.

Discussion

Loading…