Site Logo
Find Your Local Branch

Software Development

Learn | jQuery Course: Beginner to Intermediate

What it is

jQuery is a JavaScript library. It gives you short, easy tools to work with HTML, CSS, and events (like clicks).

Why it is used (real-life example)

If you want to hide a menu when a button is clicked, jQuery can do it with very little code.

Step-by-step

  • Step 1: Load jQuery in your page.
  • Step 2: Wait until the page is ready.
  • Step 3: Select an element and do something (like hide it).

Code examples

Example 1: Load jQuery and run code when ready
<!doctype html><html><head><meta charset="utf-8"><title>jQuery Purpose</title><script src="https://code.jquery.com/jquery-3.7.1.min.js"></script></head><body><h1 id="msg">Hello</h1><script>
$(function () {
$('#msg').text('Hello from jQuery');
});
</script></body></html>
Example 2: Click a button to hide a box
<button id="hideBtn">Hide</button><div id="box">I am a box</div><script>
$(function () {
$('#hideBtn').on('click', function () {
$('#box').hide();
});
});
</script>

Common mistakes

  • Running jQuery code before the library loads.
  • Running code before the HTML elements exist (not using a ready function).
  • Forgetting the # when selecting by id.

Tips / best practices

  • Place your custom script after loading jQuery.
  • Wrap code in $(function(){ ... }) to wait for the page.
  • Keep selectors simple and clear.

What it is

The “ready” idea means: run your jQuery code only after the page HTML is loaded. This helps your code find elements safely.

Why it is used (real-life example)

If you try to attach a click handler to a button before the button exists, nothing will happen. Ready makes sure the button is there first.

Step-by-step

  • Step 1: Put your page HTML (like buttons and divs).
  • Step 2: Use $(function(){ ... }) to wrap your code.
  • Step 3: Inside, add event handlers and changes.

Code examples

Example 1: Short ready syntax
<h2 id="status">Waiting...</h2><script>
$(function () {
$('#status').text('DOM is ready');
});
</script>
Example 2: Document ready syntax
<button id="btn">Click me</button><script>
$(document).ready(function () {
$('#btn').on('click', function () {
alert('Button works because DOM is ready');
});
});
</script>

Common mistakes

  • Writing $(document).ready but forgetting the parentheses ().
  • Placing jQuery code in the <head> without ready and expecting it to work.
  • Using $ before jQuery is loaded.

Tips / best practices

  • Prefer the short form $(function(){ ... }) for simple pages.
  • Keep one ready block per file when possible, to stay organized.
  • If you load HTML later (AJAX), you may need event delegation (covered later).

What it is

A selector is a pattern that finds elements in the page. jQuery uses CSS-style selectors, like #id, .class, and tag names.

Why it is used (real-life example)

If you want to change the text of all items in a list, you first select them, then apply the change.

Step-by-step

  • Step 1: Pick the element you want (by id, class, or tag).
  • Step 2: Use $('...') to select it.
  • Step 3: Call an action like text() or addClass().

Code examples

Example 1: Select by id and class
<p id="one">First</p><p class="note">Second</p><p class="note">Third</p><script>
$(function () {
$('#one').text('Changed only the first');
$('.note').addClass('highlight');
});
</script>
Example 2: Select inside another element
<div id="menu">
<a href="#">Home</a>
<a href="#">About</a>
</div><script>
$(function () {
$('#menu a').first().text('Start');
$('#menu a').last().css('font-weight', 'bold');
});
</script>

Common mistakes

  • Forgetting # for ids and . for classes.
  • Using a selector that matches many elements by accident.
  • Spelling the id/class name differently than in HTML.

Tips / best practices

  • Use ids for single important elements (like one button).
  • Use classes for groups (like many cards).
  • Make selectors specific enough, like #menu a instead of just a.

Events

What it is: An event is something that happens in the browser, like a click, typing, or moving the mouse. jQuery lets you run code when an event happens.

Why it is used (real-life example): When a user clicks a “Buy” button, you can show a message or add an item to a cart.

Step-by-step
  • Pick the element you want to listen to.
  • Choose the event (like click).
  • Attach a function that runs when the event happens.
  • Inside the function, write the action you want.
Code example 1: click
$(function(){
$('#buyBtn').on('click', function(){
alert('Added to cart');
});
});

Explanation: $(function(){ ... }) waits until the page is ready. $('#buyBtn') finds the button. .on('click', ...) runs the function when the button is clicked.

Code example 2: keyboard input
$(function(){
$('#nameInput').on('keyup', function(){
var text = $(this).val();
$('#preview').text(text);
});
});

Explanation: keyup runs after the user releases a key. $(this) is the input that triggered the event. .val() reads the input value. .text() updates the preview text.

Common mistakes
  • Binding events before the element exists on the page. Use $(function(){ ... }) or event delegation later.
  • Forgetting the # in an id selector, so jQuery cannot find the element.
  • Using click() many times and accidentally adding multiple handlers. This causes the action to run multiple times.
Tips / best practices
  • Prefer .on() because it is flexible and works well with delegation.
  • Keep event functions short. Call other functions for bigger work.
  • Use clear names like #saveBtn and #searchInput to make code easy to read.

Text

What it is: Working with text means reading or changing the visible words inside an element. In jQuery, you often use .text() for plain text.

Why it is used (real-life example): When a user submits a form, you can show “Saved!” or display an error message.

Step-by-step
  • Select the element that holds the text.
  • To read text, call .text() with no value.
  • To set text, pass a string to .text('...').
  • Check the result in the page to confirm it changed.
Code example 1: set a message
$(function(){
$('#saveBtn').on('click', function(){
$('#status').text('Saved successfully');
});
});

Explanation: When the button is clicked, jQuery finds #status and replaces its visible text.

Code example 2: read text and use it
$(function(){
$('#checkBtn').on('click', function(){
var current = $('#status').text();
if(current === 'Saved successfully'){
alert('Everything is saved');
}
});
});

Explanation: $('#status').text() reads the current text. Then a simple if checks the value and shows an alert.

Common mistakes
  • Using .html() when you only need text. That can lead to unexpected HTML changes.
  • Comparing text with extra spaces or line breaks. The read value must match exactly.
  • Trying to read text from an input using .text(). Inputs use .val() instead.
Tips / best practices
  • Use .text() for user-visible messages to avoid injecting HTML by mistake.
  • Keep messages short and clear for users.
  • If you update the same message many times, store common text in variables to reduce repeated strings.

HTML

What it is: Working with HTML means reading or changing the markup inside an element. In jQuery, you use .html() to get or set inner HTML.

Why it is used (real-life example): You can build a small list of search results and show it inside a container.

Step-by-step
  • Select the container element (like a div or ul).
  • To insert HTML, create a string that contains tags.
  • Set it using .html('<strong>...</strong>').
  • Check that the browser renders the tags as elements, not as plain text.
Code example 1: insert a simple card
$(function(){
$('#showCard').on('click', function(){
var card = '
Plan: Basic
';
$('#box').html(card);
});
});

Explanation: The string contains HTML tags. $('#box').html(card) replaces everything inside #box with that HTML.

Code example 2: read HTML and append more
$(function(){
$('#addItem').on('click', function(){
var current = $('#list').html();
var next = current + '
  • New item
  • ';
    $('#list').html(next);
    });
    });

    Explanation: First we read the current inner HTML. Then we add a new <li> string and set it back.

    Common mistakes
    • Putting user input directly into .html(). This can create security problems (XSS).
    • Forgetting closing tags in your HTML string, which can break the page layout.
    • Using .html() when you mean .text(), causing tags to be interpreted as real elements.
    Tips / best practices
    • Use .text() for plain text, and .html() only when you truly need markup.
    • If you must include user content, insert it as text (or sanitize it) instead of raw HTML.
    • Prefer building elements with jQuery (later in the course) instead of long HTML strings, to reduce errors.

    Attributes

    What it is: An attribute is extra information on an HTML element. Examples are href, src, id, and title. In jQuery, you can read or change attributes using .attr() and remove them using .removeAttr().

    Why it is used (real-life example): You might want to change a link URL after the user picks a product, or swap an image when a user chooses a color.

    Step-by-step
    • Pick the element you want to change.
    • Read the current attribute value with .attr(name).
    • Set a new value with .attr(name, value).
    • If needed, remove an attribute with .removeAttr(name).
    Code example 1: Read and set a link attribute
    <a id="helpLink" href="https://example.com/help">Help</a>
    <button id="changeLink">Go to Support</button>
    <script>
    $(function () {
    var oldUrl = $("#helpLink").attr("href");
    console.log("Old URL:", oldUrl);

    $("#changeLink").on("click", function () {
    $("#helpLink").attr("href", "https://example.com/support");
    $("#helpLink").attr("title", "Open Support Page");
    });
    });
    </script>

    Explanation: First we read the current href. Then on button click, we set a new href and also add a title attribute.

    Code example 2: Swap an image using src
    <img id="productImg" src="img/blue-shirt.png" alt="Shirt">
    <button id="setRed">Red</button>
    <button id="removeAlt">Remove alt</button>
    <script>
    $(function () {
    $("#setRed").on("click", function () {
    $("#productImg").attr("src", "img/red-shirt.png");
    });

    $("#removeAlt").on("click", function () {
    $("#productImg").removeAttr("alt");
    });
    });
    </script>

    Explanation: Clicking Red changes the image file by setting src. The second button removes the alt attribute.

    Common mistakes
    • Confusing attributes with CSS: style is different from normal attributes like href.
    • Trying to set an attribute on the wrong element (for example, setting href on a div).
    • Forgetting that .attr(name) reads only the first matched element.
    Tips / best practices
    • Use attributes for element data like URLs, image paths, and accessibility text.
    • When you only need a boolean state (like checked/selected), prefer property methods (covered later) instead of attributes.
    • Keep attribute names correct and lowercase (like href, src).

    CSS

    What it is: CSS controls how elements look (colors, sizes, spacing). In jQuery, you can read or change CSS with .css(). You can also add or remove CSS classes using .addClass(), .removeClass(), and .toggleClass().

    Why it is used (real-life example): You can highlight a wrong input field in red, or change the theme when a user clicks a button.

    Step-by-step
    • Create CSS rules (classes) in your stylesheet.
    • Use jQuery to add or remove those classes when something happens.
    • For small one-time changes, use .css() to set a style directly.
    • Test the result and keep styles consistent.
    Code example 1: Add and remove a highlight class
    <style>
    .highlight {
    background: #fff3cd;
    border: 1px solid #f0ad4e;
    padding: 8px;
    }
    </style>
    <div id="note">Read this message.</div>
    <button id="on">Highlight</button>
    <button id="off">Remove</button>
    <script>
    $(function () {
    $("#on").on("click", function () {
    $("#note").addClass("highlight");
    });
    $("#off").on("click", function () {
    $("#note").removeClass("highlight");
    });
    });
    </script>

    Explanation: The CSS class highlight describes the look. jQuery only adds or removes that class, so your JavaScript stays simple.

    Code example 2: Change a single CSS property with .css()
    <div id="box" style="width:120px;height:60px;background:#e7f1ff;"></div>
    <button id="widen">Widen</button>
    <button id="readWidth">Read width</button>
    <script>
    $(function () {
    $("#widen").on("click", function () {
    $("#box").css("width", "200px");
    });

    $("#readWidth").on("click", function () {
    var w = $("#box").css("width");
    console.log("Current width:", w);
    });
    });
    </script>

    Explanation: .css("width") reads a value (often as a string like 200px). .css("width", "200px") sets the value.

    Common mistakes
    • Forgetting units like px when setting sizes as strings.
    • Using .css() everywhere instead of classes, which can make styles messy.
    • Writing CSS property names in the wrong format (use background-color as a string).
    Tips / best practices
    • Prefer .addClass() and .removeClass() for most styling changes.
    • Use .toggleClass() for on/off UI states like menus or dark mode.
    • Keep your CSS in a stylesheet so it is easy to maintain.

    Dimensions

    What it is: Dimensions are the size of an element. jQuery can read or set sizes using .width() and .height(). It can also include padding and border using .innerWidth() and .outerWidth() (same for height).

    Why it is used (real-life example): You may want to size a sidebar to match the height of the main content, or check if a card is too small to show all text.

    Step-by-step
    • Select the element you want to measure.
    • Read its width/height to understand the current layout.
    • Change the size with .width(number) or .height(number) (numbers are pixels).
    • If you need padding/border, use inner/outer methods.
    Code example 1: Read and show element size
    <div id="panel" style="width:180px;height:90px;padding:10px;border:2px solid #333;">Panel</div>
    <button id="measure">Measure</button>
    <div id="out"></div>
    <script>
    $(function () {
    $("#measure").on("click", function () {
    var w = $("#panel").width();
    var h = $("#panel").height();
    var innerW = $("#panel").innerWidth();
    var outerW = $("#panel").outerWidth();

    $("#out").text("width=" + w + ", height=" + h + ", innerWidth=" + innerW + ", outerWidth=" + outerW);
    });
    });
    </script>

    Explanation: width() and height() measure the content box. innerWidth() includes padding, and outerWidth() includes border (and optionally margin if you pass true).

    Code example 2: Set a size based on another element
    <div id="left" style="width:140px;height:140px;background:#dff0d8;">Left</div>
    <div id="right" style="width:140px;height:60px;background:#d9edf7;">Right</div>
    <button id="match">Match right to left height</button>
    <script>
    $(function () {
    $("#match").on("click", function () {
    var leftH = $("#left").height();
    $("#right").height(leftH);
    });
    });
    </script>

    Explanation: We read the left element height (a number in pixels). Then we set the right element height to the same number.

    Common mistakes
    • Expecting width() to include padding and border (it does not).
    • Setting width/height with strings like "200px" in .width() (it expects a number).
    • Measuring an element that is hidden (it may return 0).
    Tips / best practices
    • Use dimension methods for quick UI sizing, but prefer CSS layout (flex/grid) when possible.
    • If you must measure after content loads (like images), measure after the content is available.
    • Know which box you need: content (width), padding (innerWidth), or border (outerWidth).

    Traversal

    What it is: Traversal means moving around the page structure (the DOM). You start from one element and then go to its parent, children, or nearby elements.

    Why it is used (real-life example): In a product list, when a user clicks “Add”, you may need to find the product name in the same row without using a long selector.

    Step-by-step
    • Pick a starting element with a selector.
    • Move to related elements using traversal methods like parent(), children(), find(), closest(), next(), and prev().
    • Do something with the found element (read text, add a class, change content).
    Code example 1: find item text inside the same card
    <div class="card"><h3 class="name">Coffee</h3><button class="add">Add</button></div>

    $(document).on('click', '.add', function () {
    // Start from the clicked button
    var name = $(this).closest('.card').find('.name').text();
    alert('Added: ' + name);
    });

    Explanation: $(this) is the clicked button. closest('.card') moves up to the card. find('.name') searches inside the card for the name.

    Code example 2: move between siblings
    <ul>
    <li class="item active">One</li>
    <li class="item">Two</li>
    <li class="item">Three</li>
    </ul>

    // Select the active item and highlight the next one
    var $next = $('.item.active').next('.item');
    $next.addClass('active');
    $('.item.active').first().removeClass('active');

    Explanation: next('.item') gets the next sibling that matches .item. Then we add a class to show it as active.

    Common mistakes
    • Using parent() when you really need closest() (parent is only one level up).
    • Calling find() on the wrong starting element, so nothing is found.
    • Writing very long selectors instead of using traversal, making code hard to maintain.
    Tips / best practices
    • Use closest() for “go up until you reach a container”.
    • Store results in variables like var $card = ... to avoid repeating work.
    • Keep HTML structure predictable (cards, rows, list items) so traversal stays simple.

    Classes

    What it is: A class is a label on an element (like class="active"). jQuery can add, remove, toggle, and check classes.

    Why it is used (real-life example): When a user selects a menu item, you add an active class to highlight it. This keeps style in CSS and logic in JavaScript.

    Step-by-step
    • Select the element you want to change.
    • Use addClass() to add a class, removeClass() to remove it.
    • Use toggleClass() to switch it on/off.
    • Use hasClass() to check if it is already there.
    Code example 1: active menu item
    <ul id="menu">
    <li class="link">Home</li>
    <li class="link">Shop</li>
    <li class="link">Contact</li>
    </ul>

    $('#menu').on('click', '.link', function () {
    // Remove active from all links
    $('#menu .link').removeClass('active');
    // Add active to the clicked link
    $(this).addClass('active');
    });

    Explanation: First we clear the old selection, then we mark the clicked item. This prevents multiple items being active.

    Code example 2: toggle a dark mode class
    <button id="darkBtn">Toggle dark mode</button>
    <div id="page">Content...</div>

    $('#darkBtn').on('click', function () {
    $('#page').toggleClass('dark');
    if ($('#page').hasClass('dark')) {
    console.log('Dark mode ON');
    } else {
    console.log('Dark mode OFF');
    }
    });

    Explanation: toggleClass('dark') adds the class if missing, or removes it if it exists. hasClass() checks the current state.

    Common mistakes
    • Trying to style by setting many inline styles instead of using a class.
    • Forgetting to remove an old class, so multiple states are active at once.
    • Using spaces incorrectly in class names (classes are separated by spaces, a single class name cannot contain spaces).
    Tips / best practices
    • Use classes for states: active, open, error.
    • Keep styling rules in CSS, and only switch classes in jQuery.
    • Use event delegation (like $('#menu').on('click', '.link', ...)) if items can be added later.

    Animation

    What it is: Animation is a smooth visual change over time. In jQuery, you can show/hide with movement, fade, slide, or animate numeric CSS values.

    Why it is used (real-life example): When opening a help panel, sliding it down feels clearer than instantly appearing. It helps users notice what changed.

    Step-by-step
    • Select the element you want to animate.
    • Choose a simple effect: fadeIn()/fadeOut() or slideDown()/slideUp().
    • Set a duration (for example 200 or 400 milliseconds).
    • Optionally run code after the animation using a callback function.
    Code example 1: fade a message
    <button id="saveBtn">Save</button>
    <div id="msg" style="display:none;">Saved!</div>

    $('#saveBtn').on('click', function () {
    $('#msg').fadeIn(200, function () {
    // This runs after fadeIn is finished
    setTimeout(function () {
    $('#msg').fadeOut(200);
    }, 800);
    });
    });

    Explanation: The message fades in, waits a bit, then fades out. The callback makes sure the waiting starts after the fade-in ends.

    Code example 2: slide a panel
    <button id="helpBtn">Help</button>
    <div id="helpPanel" style="display:none;">
    <p>Here is some help text.</p>
    </div>

    $('#helpBtn').on('click', function () {
    $('#helpPanel').slideToggle(300);
    });

    Explanation: slideToggle() opens the panel if it is closed, and closes it if it is open.

    Common mistakes
    • Calling many animations quickly without stopping, causing a long queue.
    • Animating properties that are not numeric (many cannot be animated).
    • Using very slow durations, which can annoy users.
    Tips / best practices
    • Use short durations (like 150–400ms) for most UI actions.
    • If users can click fast, consider stop(true, true) before starting a new animation.
    • Prefer simple effects (fade/slide) for clear, beginner-friendly UI behavior.

    Ajax

    What it is: Ajax in jQuery lets your page talk to a server and get data without reloading the whole page.

    Why it is used (real-life example): When you click “Load more comments”, the page can download new comments in the background and show them instantly.

    Step-by-step
    • Pick a URL that returns data (often JSON).
    • Call a jQuery Ajax method.
    • Wait for success (data arrives) or failure (error).
    • Update the page using the returned data.
    Code example 1: Load HTML into a div
    $(function() {
    // When the button is clicked, we fetch HTML and put it into #result
    $('#loadBtn').on('click', function() {
    $('#result').load('/partials/help.html', function(responseText, statusText) {
    if (statusText === 'error') {
    $('#result').text('Could not load content.');
    }
    });
    });
    });

    Explain: .load() sends a request to the server. If it works, the HTML response is inserted into #result. If it fails, we show a simple message.

    Code example 2: Get JSON and render a list
    $(function() {
    $('#usersBtn').on('click', function() {
    $.getJSON('/api/users', function(users) {
    // users is expected to be an array like: [{ name: 'Ava' }, { name: 'Liam' }]
    var items = users.map(function(u) {
    return '
  • ' + u.name + '
  • ';
    }).join('');
    $('#users').html(items);
    }).fail(function() {
    $('#users').html('
  • Could not load users.
  • ');
    });
    });
    });

    Explain: $.getJSON() downloads JSON. We turn the array into <li> items and insert them into the page.

    Common mistakes
    • Calling an API that blocks cross-domain requests (CORS). The browser may refuse it.
    • Forgetting error handling, so the UI stays empty when the request fails.
    • Expecting JSON but the server returns HTML (or the opposite).
    Tips / best practices
    • Always show a loading state (like “Loading...”) so users know something is happening.
    • Use .fail() (or error callbacks) to handle problems clearly.
    • Keep DOM updates small: build HTML strings first, then insert once.

    Forms

    What it is: Form handling means reading what the user typed, checking it, and deciding what to do next (submit, show errors, or send with Ajax).

    Why it is used (real-life example): A sign-up form should stop empty email fields and show a clear message before sending data to the server.

    Step-by-step
    • Listen for the form submit event.
    • Stop the default submit when you want to validate first.
    • Read values from inputs.
    • Show simple error messages if needed.
    • Submit normally or send data with Ajax.
    Code example 1: Simple validation on submit
    $(function() {
    $('#signupForm').on('submit', function(e) {
    var email = $('#email').val();
    var password = $('#password').val();

    // Stop submit first, then allow it only when valid
    e.preventDefault();
    $('#error').text('');

    if (!email) {
    $('#error').text('Email is required.');
    return;
    }
    if (password.length < 6) {
    $('#error').text('Password must be at least 6 characters.');
    return;
    }

    // If we reach here, the form is OK
    this.submit();
    });
    });

    Explain: We stop the browser submit with e.preventDefault(). Then we check values. If everything is valid, we call this.submit() to submit for real.

    Code example 2: Read form data with serialize
    $(function() {
    $('#contactForm').on('submit', function(e) {
    e.preventDefault();

    // Turns inputs into a query string like: name=Ava&message=Hi
    var data = $(this).serialize();

    $.post('/contact', data)
    .done(function() {
    $('#status').text('Message sent.');
    })
    .fail(function() {
    $('#status').text('Could not send message.');
    });
    });
    });

    Explain: serialize() collects form fields with name attributes. Then $.post() sends the data to the server.

    Common mistakes
    • Inputs missing a name attribute. Then serialize() will skip them.
    • Validating only on the client. The server must still validate too.
    • Forgetting to reset old error text, so the user sees outdated messages.
    Tips / best practices
    • Keep messages short and near the input, so users know what to fix.
    • Validate one rule at a time and explain it in simple words.
    • Disable the submit button while sending to prevent double submits.

    Plugins

    What it is: A jQuery plugin is a reusable function that adds a new method to jQuery. It lets you apply the same behavior to many elements with one simple call.

    Why it is used (real-life example): If many pages need the same “highlight on click” behavior, a plugin keeps your code clean and consistent.

    Step-by-step
    • Create a function on $.fn (this is where jQuery methods live).
    • Inside the plugin, this is the jQuery collection (the selected elements).
    • Return this so the method can be chained (like $('.a').myPlugin().addClass('x')).
    • Allow options, with simple default values.
    Code example 1: A tiny highlight plugin
    (function($) {
    $.fn.highlight = function(color) {
    var c = color || 'yellow';
    return this.each(function() {
    $(this).css('background-color', c);
    });
    };
    })(jQuery);

    // Usage:
    $(function() {
    $('.note').highlight('lightgreen');
    });

    Explain: We add a new method called highlight. It loops over every matched element with each() and sets a background color. Returning this keeps chaining working.

    Code example 2: Plugin with options
    (function($) {
    $.fn.clickLabel = function(options) {
    var settings = $.extend({
    prefix: 'Clicked: ',
    target: null
    }, options);

    return this.each(function() {
    var $el = $(this);
    $el.on('click', function() {
    var text = settings.prefix + $el.text();
    if (settings.target) {
    $(settings.target).text(text);
    } else {
    $el.attr('data-clicked', 'true');
    }
    });
    });
    };
    })(jQuery);

    // Usage:
    $(function() {
    $('.item').clickLabel({ target: '#status' });
    });

    Explain: $.extend() merges default settings with user options. The plugin then attaches a click handler. On click, it writes a message into #status (if provided).

    Common mistakes
    • Not returning this. Then chaining breaks.
    • Using global variables inside the plugin, which can conflict with other code.
    • Binding events multiple times if you call the plugin repeatedly without cleanup.
    Tips / best practices
    • Keep plugin behavior small and focused (one job).
    • Use options with defaults so beginners can use it quickly.
    • Use this.each() so the plugin works on many elements.

    Deferred

    What it is: A Deferred is a small object in jQuery that helps you handle something that finishes later, like a timer or a request. It can be resolved (success) or rejected (fail).

    Why it is used (real-life example): Imagine you order food. You do not get it right away. You want a clear way to run code when the food arrives (success) or when the order fails (error). Deferred helps you do that in code.

    Step-by-step
    • Create a Deferred with $.Deferred().
    • Attach handlers with .done() and .fail().
    • Later, call resolve(value) or reject(error).
    • Your handlers run when the Deferred changes state.
    Code example 1: create and resolve
    function wait(ms) {
    var d = $.Deferred();
    setTimeout(function() {
    d.resolve("Finished after " + ms + "ms");
    }, ms);
    return d.promise();
    }

    wait(500).done(function(msg) {
    console.log(msg);
    });

    Explanation: wait returns a promise so other code can only listen, not resolve it. After 500ms, we call resolve, so .done runs.

    Code example 2: reject on a condition
    function checkAge(age) {
    var d = $.Deferred();
    if (age >= 18) {
    d.resolve("Access allowed");
    } else {
    d.reject("Access denied");
    }
    return d.promise();
    }

    checkAge(16)
    .done(function(msg) { console.log(msg); })
    .fail(function(err) { console.log(err); });

    Explanation: We resolve for ages 18+ and reject otherwise. The correct handler runs based on the state.

    Common mistakes
    • Returning the Deferred itself instead of a promise. This lets other code resolve/reject it by mistake.
    • Calling resolve and reject multiple times and expecting it to run again (it runs only the first time).
    • Forgetting to add .fail() and then not seeing errors.
    Tips / best practices
    • Return d.promise() to protect your Deferred.
    • Always handle both success and failure for clearer behavior.
    • Use clear messages or objects when resolving/rejecting so debugging is easier.

    Promise

    What it is: A Promise (in jQuery) is the read-only side of a Deferred. It lets you listen for success or failure, but it does not let you change the result.

    Why it is used (real-life example): When you track a delivery, you can only watch the status. You cannot change the delivery system yourself. A promise is like that: you can react to the result safely.

    Step-by-step
    • Create a Deferred internally.
    • Return promise() to outside code.
    • Outside code uses .then(), .done(), and .fail().
    • Only the creator can resolve/reject the Deferred.
    Code example 1: return a promise from a function
    function loadUserName() {
    var d = $.Deferred();
    setTimeout(function() {
    d.resolve("Sam");
    }, 300);
    return d.promise();
    }

    var p = loadUserName();
    p.done(function(name) {
    console.log("Hello, " + name);
    });

    Explanation: p is a promise. You can attach handlers, but you cannot call resolve on it.

    Code example 2: use then to transform a value
    function getPrice() {
    var d = $.Deferred();
    setTimeout(function() {
    d.resolve(10);
    }, 200);
    return d.promise();
    }

    getPrice()
    .then(function(price) {
    return price * 1.2;
    })
    .done(function(total) {
    console.log("Total: " + total);
    });

    Explanation: then can return a new value. The next handler receives the new value.

    Common mistakes
    • Trying to call resolve on a promise (it does not exist).
    • Mixing up done/fail with then without understanding the flow.
    • Forgetting that async code runs later, so variables may not be ready yet.
    Tips / best practices
    • Return promises from functions that do async work. This keeps code clean.
    • Prefer returning promises to avoid other code changing your async state.
    • Keep each then step small: one transform per step.

    Callbacks

    What it is: $.Callbacks() is a tool to create a list of functions (callbacks) and run them together. You can add, remove, and fire the list.

    Why it is used (real-life example): Think of a notification list in an app. Many parts of the app want to react when something happens (like “user logged in”). Callbacks lets you register many reactions and trigger them all at once.

    Step-by-step
    • Create a callback list: var list = $.Callbacks().
    • Add functions using list.add(fn).
    • Trigger them using list.fire(args...).
    • Optional flags like once or memory change behavior.
    Code example 1: basic add and fire
    var list = $.Callbacks();

    function logA(msg) {
    console.log("A: " + msg);
    }
    function logB(msg) {
    console.log("B: " + msg);
    }

    list.add(logA);
    list.add(logB);

    list.fire("Hello");

    Explanation: We add two functions to the list. When we fire with "Hello", both functions run in the order they were added.

    Code example 2: memory flag
    var list = $.Callbacks("memory");

    list.fire("Saved");

    list.add(function(msg) {
    console.log("Late listener: " + msg);
    });

    Explanation: With memory, the list remembers the last fired values. When we add a function later, it runs immediately with the saved message.

    Common mistakes
    • Using Callbacks when a simple direct function call would be enough.
    • Forgetting that once prevents firing more than one time.
    • Adding anonymous functions and then not being able to remove them later.
    Tips / best practices
    • Name your callback functions when possible so you can remove them if needed.
    • Use flags carefully: memory is helpful for “ready” style events, but can surprise you if you do not expect late calls.
    • Keep callback functions small and focused to avoid hard-to-debug chains.

    Data

    What it is: jQuery .data() lets you store small pieces of information on an element. It is like attaching a note to the element in memory.

    Why it is used (real-life example): On a shopping page, each “Add” button can store a product id. When you click, you read the id and add that item to the cart.

    Step-by-step
    • Select an element with jQuery.
    • Save a value using .data(key, value).
    • Read it later using .data(key).
    • Remember: .data() is mostly for JavaScript memory storage. It is not the same as changing HTML attributes.
    Code example 1: store and read a value
    // HTML: <button id="buy">Buy</button>

    $(function () {
    $("#buy").data("productId", 42);

    $("#buy").on("click", function () {
    var id = $(this).data("productId");
    alert("Buying product: " + id);
    });
    });

    Explanation: We save productId on the button. When the button is clicked, $(this).data("productId") reads it back.

    Code example 2: using HTML data-* attributes
    // HTML: <button class="item" data-sku="SKU-100">Add</button>

    $(function () {
    $(".item").on("click", function () {
    // jQuery can read data-* as camelCase keys
    var sku = $(this).data("sku");
    console.log("SKU:", sku);
    });
    });

    Explanation: The button has data-sku in HTML. jQuery reads it with .data("sku").

    Common mistakes
    • Expecting .data() to always update the HTML attribute. It usually stores in memory, not in the DOM attribute.
    • Mixing keys like product-id and productId. Use one style consistently.
    • Storing big objects on many elements. This can waste memory.
    Tips / best practices
    • Store small, simple values (ids, flags, small settings).
    • Prefer HTML data-* for values that should be visible in markup, and .data() for temporary runtime values.
    • Use clear key names like productId or isOpen.

    Queue

    What it is: A queue is a waiting line of actions for an element. In jQuery, effects (like simple animations) can be placed in a queue so they run one after another.

    Why it is used (real-life example): You want a notification box to run actions in order: show, wait, then hide. A queue helps you keep the order without messy timing code.

    Step-by-step
    • Pick an element.
    • Add a custom queued step using .queue(function(next){ ...; next(); }).
    • Call next() when your step is done, so the queue can continue.
    • Use .dequeue() to start a custom queue if needed.
    Code example 1: custom steps with next()
    // HTML: <div id="note">Saved!</div>

    $(function () {
    var $note = $("#note");

    $note.queue(function (next) {
    $note.show();
    next();
    });

    $note.queue(function (next) {
    setTimeout(function () {
    next();
    }, 1000);
    });

    $note.queue(function (next) {
    $note.hide();
    next();
    });
    });

    Explanation: We add three steps. Each step calls next() to let the next step run. The middle step waits 1 second using setTimeout.

    Code example 2: clearing a queue
    // HTML: <button id="stop">Stop</button>
    // HTML: <div id="box">Box</div>

    $(function () {
    var $box = $("#box");

    // Add many queued steps
    $box.queue(function (next) { console.log("Step 1"); next(); });
    $box.queue(function (next) { console.log("Step 2"); next(); });

    $("#stop").on("click", function () {
    $box.clearQueue();
    console.log("Queue cleared");
    });
    });

    Explanation: clearQueue() removes waiting steps that have not run yet. This is useful when the user cancels an action.

    Common mistakes
    • Forgetting to call next(). The queue will freeze and later steps will never run.
    • Using long setTimeout delays without a cancel plan. The UI can feel stuck.
    • Assuming queues are global. They are tied to each element.
    Tips / best practices
    • Keep queued steps short and clear.
    • Always call next() (even after async work).
    • Provide a way to cancel or clear queued work for better UX.

    Utilities

    What it is: jQuery utilities are small helper functions like $.each() and $.extend(). They help you work with arrays, objects, and settings.

    Why it is used (real-life example): When you build a small widget, you may want default options. $.extend() lets you merge user options with your defaults.

    Step-by-step
    • Use $.each(list, function(index, value){ ... }) to loop over arrays or objects.
    • Use $.extend(target, source) to copy properties into a target object.
    • For safe defaults, merge into a new object so you do not change your original defaults.
    Code example 1: looping with $.each()
    $(function () {
    var names = ["Ana", "Ben", "Chen"];

    $.each(names, function (index, value) {
    console.log(index + " => " + value);
    });

    var prices = { apple: 2, orange: 3 };
    $.each(prices, function (key, value) {
    console.log(key + " costs " + value);
    });
    });

    Explanation: For arrays, you get index and value. For objects, you get key and value.

    Code example 2: merging options with $.extend()
    $(function () {
    var defaults = {
    color: "blue",
    size: "medium"
    };

    var userOptions = { color: "green" };

    // Merge into a new object to keep defaults safe
    var settings = $.extend({}, defaults, userOptions);

    console.log(settings.color); // green
    console.log(settings.size); // medium
    });

    Explanation: $.extend({}, defaults, userOptions) creates a new object. User values overwrite default values when keys match.

    Common mistakes
    • Changing your defaults by doing $.extend(defaults, userOptions). This mutates defaults.
    • Confusing $.each() with $(selector).each(). One is a general utility, the other loops over matched elements.
    • Forgetting that $.extend() is shallow by default (nested objects are not deeply cloned).
    Tips / best practices
    • Use $.extend({}, ...) for safe option merging.
    • Keep utility loops small and readable. Complex loops are better as separate functions.
    • Name option keys clearly (like color, duration, theme).