Lesson 19: jQuery Arithmetic

Master jQuery arithmetic operations with practical examples. Learn to perform calculations, manipulate numbers, and build interactive calculators.

Understanding jQuery Arithmetic

jQuery uses JavaScript's arithmetic operators to perform calculations. These operations are essential for dynamic content, animations, and interactive features.

Key Arithmetic Operators:
  • + - Addition
  • - - Subtraction
  • * - Multiplication
  • / - Division
  • % - Modulus (remainder)
  • ++ - Increment
  • -- - Decrement
Operator Description Example
+ Adds numbers or concatenates strings 5 + 3 // returns 8
- Subtracts numbers 10 - 4 // returns 6
* Multiplies numbers 3 * 4 // returns 12
/ Divides numbers 15 / 3 // returns 5
% Returns division remainder 10 % 3 // returns 1

Basic Arithmetic Operations

jQuery can perform arithmetic operations on numbers extracted from DOM elements or variables.

Example 19.1: Performing Basic Calculations

Calculate results using values from input fields:

Results will appear here
// Basic arithmetic examples
$("#add-btn").click(function() {
    const num1 = parseFloat($("#num1").val());
    const num2 = parseFloat($("#num2").val());
    const result = num1 + num2;
    $("#calc-result").text(`${num1} + ${num2} = ${result}`);
});

$("#subtract-btn").click(function() {
    const num1 = parseFloat($("#num1").val());
    const num2 = parseFloat($("#num2").val());
    const result = num1 - num2;
    $("#calc-result").text(`${num1} - ${num2} = ${result}`);
});

$("#multiply-btn").click(function() {
    const num1 = parseFloat($("#num1").val());
    const num2 = parseFloat($("#num2").val());
    const result = num1 * num2;
    $("#calc-result").text(`${num1} × ${num2} = ${result}`);
});

$("#divide-btn").click(function() {
    const num1 = parseFloat($("#num1").val());
    const num2 = parseFloat($("#num2").val());
    
    if (num2 === 0) {
        $("#calc-result").text("Cannot divide by zero!");
    } else {
        const result = num1 / num2;
        $("#calc-result").text(`${num1} ÷ ${num2} = ${result.toFixed(2)}`);
    }
});

Arithmetic in Animation

Arithmetic operations are essential for creating dynamic animations and size manipulations.

Example 19.2: Using Arithmetic in Animations

Resize elements using arithmetic operations:

Resize Me!
// Using arithmetic in animations
$("#increase-btn").click(function() {
    const $box = $("#resizable-box");
    const currentWidth = parseInt($box.css("width"));
    const currentHeight = parseInt($box.css("height"));
    
    $box.animate({
        width: currentWidth * 1.2 + "px",
        height: currentHeight * 1.2 + "px"
    }, 500);
});

$("#decrease-btn").click(function() {
    const $box = $("#resizable-box");
    const currentWidth = parseInt($box.css("width"));
    const currentHeight = parseInt($box.css("height"));
    
    if (currentWidth > 50 && currentHeight > 30) {
        $box.animate({
            width: currentWidth * 0.8 + "px",
            height: currentHeight * 0.8 + "px"
        }, 500);
    }
});

$("#reset-size-btn").click(function() {
    $("#resizable-box").animate({
        width: "200px",
        height: "100px"
    }, 500);
});

Building a Calculator

Create a fully functional calculator using jQuery arithmetic operations.

Example 19.3: jQuery Calculator

0
// jQuery Calculator Implementation
let currentInput = '0';
let previousInput = '';
let operation = null;
let shouldResetScreen = false;

$(".calculator-key").click(function() {
    const value = $(this).data("value") || $(this).text();
    
    if ($(this).hasClass("clear")) {
        resetCalculator();
        return;
    }
    
    if ($(this).hasClass("operator")) {
        handleOperator(value);
        return;
    }
    
    if ($(this).hasClass("equals")) {
        calculateResult();
        return;
    }
    
    handleNumberInput(value);
});

function handleNumberInput(value) {
    if (currentInput === '0' || shouldResetScreen) {
        currentInput = value;
        shouldResetScreen = false;
    } else {
        currentInput += value;
    }
    updateDisplay();
}

function handleOperator(op) {
    if (operation !== null) calculateResult();
    
    previousInput = currentInput;
    operation = op;
    shouldResetScreen = true;
}

function calculateResult() {
    if (operation === null) return;
    
    const prev = parseFloat(previousInput);
    const current = parseFloat(currentInput);
    let result;
    
    switch(operation) {
        case '+':
            result = prev + current;
            break;
        case '-':
            result = prev - current;
            break;
        case '*':
            result = prev * current;
            break;
        case '/':
            result = prev / current;
            break;
        case '%':
            result = prev % current;
            break;
        default:
            return;
    }
    
    currentInput = String(result);
    operation = null;
    previousInput = '';
    updateDisplay();
}

function resetCalculator() {
    currentInput = '0';
    previousInput = '';
    operation = null;
    updateDisplay();
}

function updateDisplay() {
    $("#calc-display").text(currentInput);
}

Real-world Application: Shopping Cart

Arithmetic is essential for calculating totals in e-commerce applications.

Example 19.4: Shopping Cart Calculator

JavaScript Book

$29.99

1
jQuery Course

$49.99

1
Web Development Bundle

$89.99

1
Total: $169.97
// Shopping Cart Implementation
const prices = {
    book: 29.99,
    course: 49.99,
    bundle: 89.99
};

$(".quantity-btn").click(function() {
    const id = $(this).data("id");
    const action = $(this).data("action");
    const $qtyElement = $(`#${id}-qty`);
    let qty = parseInt($qtyElement.text());
    
    if (action === "increase") {
        qty++;
    } else if (action === "decrease" && qty > 1) {
        qty--;
    }
    
    $qtyElement.text(qty);
    calculateTotal();
});

function calculateTotal() {
    const bookQty = parseInt($("#book-qty").text());
    const courseQty = parseInt($("#course-qty").text());
    const bundleQty = parseInt($("#bundle-qty").text());
    
    const total = (bookQty * prices.book) + 
                 (courseQty * prices.course) + 
                 (bundleQty * prices.bundle);
    
    $("#cart-total").text(total.toFixed(2));
}

Best Practices

Follow these guidelines when working with arithmetic in jQuery:

  • Parse input values - Always convert string values to numbers with parseInt() or parseFloat()
  • Validate inputs - Check for NaN (Not a Number) before calculations
  • Prevent division by zero - Always check denominator before division
  • Format results - Use toFixed() for decimal precision
  • Use variables - Store intermediate results for better readability
// Best practices for jQuery arithmetic

// 1. Parse input values
const value1 = parseFloat($("#input1").val());
const value2 = parseInt($("#input2").val());

// 2. Validate inputs
if (isNaN(value1) || isNaN(value2)) {
    alert("Please enter valid numbers");
    return;
}

// 3. Prevent division by zero
if (operation === '/' && value2 === 0) {
    alert("Cannot divide by zero");
    return;
}

// 4. Format results
const result = value1 / value2;
$("#result").text(result.toFixed(2));

// 5. Use variables for clarity
const subtotal = price * quantity;
const tax = subtotal * taxRate;
const total = subtotal + tax;