JavaScript and jQuery

JavaScript and jQuery are essential technologies for modern web development. JavaScript provides interactivity to websites, while jQuery is a fast, small, and feature-rich JavaScript library that simplifies HTML document traversal, event handling, and animation.

JavaScript Basics

JavaScript is a high-level, interpreted programming language that adds dynamic behavior to web pages. Here are some fundamental aspects of JavaScript:

Creating Variables

// Using var (older method)
var name = "John";

// Using let (block-scoped)
let age = 25;

// Using const (immutable reference)
const PI = 3.14;

Data Types

// Numbers
let count = 42;
let price = 19.99;

// Strings
let greeting = "Hello, World!";
let message = 'Welcome to JavaScript';

// Booleans
let isActive = true;
let hasPermission = false;

// Arrays
let colors = ["red", "green", "blue"];

// Objects
let person = {
  firstName: "Jane",
  lastName: "Doe",
  age: 30
};

// Undefined and null
let undefinedVar;
let emptyValue = null;

Functions

// Function declaration
function greet(name) {
  return "Hello, " + name + "!";
}

// Function expression
const multiply = function(a, b) {
  return a * b;
};

// Arrow function
const add = (a, b) => a + b;

// Calling functions
console.log(greet("Alice")); // Output: Hello, Alice!
console.log(multiply(5, 3)); // Output: 15
console.log(add(7, 2));      // Output: 9

DOM Manipulation with JavaScript

The Document Object Model (DOM) represents the structure of HTML documents. JavaScript can access and modify the DOM:

// Selecting elements
const heading = document.getElementById("title");
const paragraphs = document.getElementsByTagName("p");
const buttons = document.getElementsByClassName("btn");
const firstLink = document.querySelector("a");
const allLinks = document.querySelectorAll("a");

// Modifying elements
heading.textContent = "New Title";
heading.innerHTML = "<em>Emphasized Title</em>";
heading.style.color = "blue";
heading.classList.add("highlight");

// Creating elements
const newDiv = document.createElement("div");
newDiv.textContent = "Newly created div";
document.body.appendChild(newDiv);

// Removing elements
const elementToRemove = document.getElementById("oldElement");
elementToRemove.parentNode.removeChild(elementToRemove);

Introduction to jQuery

jQuery is a JavaScript library designed to simplify HTML DOM tree traversal and manipulation, event handling, animation, and Ajax. It was created to make JavaScript programming easier and more efficient.

Including jQuery

<!-- Using CDN (recommended) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- Or local file -->
<script src="js/jquery-3.6.0.min.js"></script>

jQuery Syntax

The basic syntax of jQuery is:

$(selector).action();

Where:

  • $ is the jQuery accessor
  • selector is a CSS-style selector
  • action() is the method to perform

Selecting Elements with jQuery

jQuery makes DOM selection much simpler:

// Select by ID
$("#title");

// Select by class
$(".btn");

// Select by element type
$("p");

// Combined selectors
$("div.content");

// Pseudo-selectors
$("tr:odd");
$("a:first");

DOM Manipulation with jQuery

jQuery provides convenient methods for DOM manipulation:

// Changing content
$("#title").text("New Title");
$("#content").html("<strong>Bold text</strong>");

// Modifying attributes
$("img").attr("src", "new-image.jpg");
$("a").attr({
  href: "https://example.com",
  target: "_blank"
});

// Changing styles
$("p").css("color", "blue");
$("div").css({
  backgroundColor: "#f0f0f0",
  fontSize: "18px",
  padding: "10px"
});

// Adding/removing classes
$("button").addClass("active");
$("button").removeClass("disabled");
$("button").toggleClass("highlight");

// Appending/prepending content
$("ul").append("<li>New item</li>");
$("ul").prepend("<li>First item</li>");

Event Handling

jQuery simplifies event handling across browsers:

// Click event
$("#submitBtn").click(function() {
  alert("Button clicked!");
});

// Alternative syntax
$("#submitBtn").on("click", function() {
  alert("Button clicked!");
});

// Multiple events
$("input").on({
  focus: function() {
    $(this).css("background-color", "#f0f0f0");
  },
  blur: function() {
    $(this).css("background-color", "white");
  },
  keyup: function() {
    console.log($(this).val());
  }
});

// Document ready event
$(document).ready(function() {
  console.log("Document is ready!");
});

// Shorthand for document ready
$(function() {
  console.log("Document is ready!");
});

Animations and Effects

jQuery provides simple methods for animations and visual effects:

// Hide and show
$("#element").hide();
$("#element").show();
$("#element").toggle();

// Fade effects
$("#element").fadeIn(1000);
$("#element").fadeOut(1000);
$("#element").fadeToggle(500);

// Slide effects
$("#element").slideDown();
$("#element").slideUp();
$("#element").slideToggle();

// Custom animations
$("#element").animate({
  opacity: 0.5,
  width: "70%",
  marginLeft: "30px"
}, 1000);

// Chaining effects
$("#element")
  .slideUp(500)
  .delay(1000)
  .fadeIn(500);

AJAX with jQuery

jQuery simplifies AJAX operations across browsers:

// Basic AJAX request
$.ajax({
  url: "https://api.example.com/data",
  method: "GET",
  dataType: "json",
  success: function(response) {
    console.log("Data received:", response);
  },
  error: function(xhr, status, error) {
    console.error("Error:", error);
  }
});

// Shorthand methods
// GET request
$.get("https://api.example.com/data", function(data) {
  console.log(data);
});

// POST request
$.post("https://api.example.com/submit", {
  name: "John",
  email: "john@example.com"
}, function(response) {
  console.log(response);
});

// Load HTML into an element
$("#content").load("page.html");

jQuery Plugins

One of jQuery’s strengths is its extensibility through plugins:

// Using a plugin
$("#slider").slick({
  dots: true,
  infinite: true,
  speed: 500,
  slidesToShow: 3
});

// Creating a simple plugin
$.fn.highlight = function(color) {
  return this.each(function() {
    $(this)
      .css("background-color", color || "#ffff99")
      .css("font-weight", "bold");
  });
};

// Using your custom plugin
$("p").highlight("#ff9999");

Comparing JavaScript and jQuery

FeatureVanilla JavaScriptjQuery
SyntaxMore verboseConcise, chainable
Browser CompatibilityVaries by featureMostly handled automatically
Selecting Elementsdocument.querySelector()$() selector
Event HandlingaddEventListener().on() or event shortcuts
AnimationRequires custom codeBuilt-in methods
AJAXfetch() or XMLHttpRequest$.ajax() and shortcuts

When to Use jQuery vs. Plain JavaScript

Use jQuery when:

  • You need cross-browser compatibility with less code
  • You want to quickly prototype or build small to medium applications
  • You’re working with an older codebase that already uses jQuery
  • You need specific jQuery plugins

Use plain JavaScript when:

  • Performance is critical (jQuery adds overhead)
  • You’re building modern web applications
  • You’re using modern frameworks like React, Vue, or Angular
  • You want to minimize dependencies and bundle size

Modern JavaScript Alternatives

As modern JavaScript has evolved, many jQuery features have been incorporated into the language itself:

// jQuery vs. Modern JavaScript equivalents

// Selecting elements
// jQuery: $("#id")
// JavaScript: document.getElementById("id")

// Query multiple elements
// jQuery: $(".class")
// JavaScript: document.querySelectorAll(".class")

// Event handling
// jQuery: $("#btn").click(function() {})
// JavaScript: document.getElementById("btn").addEventListener("click", function() {})

// Ajax
// jQuery: $.ajax({url: "data.json", success: function(data) {}})
// JavaScript: fetch("data.json").then(response => response.json()).then(data => {})

jQuery in Modern Web Development

While many new projects use modern frameworks or vanilla JavaScript, jQuery continues to be used in countless websites and applications. Learning jQuery remains valuable for:

  1. Maintaining existing websites and applications
  2. Rapid prototyping
  3. Building simple sites quickly
  4. Understanding core concepts that influenced modern frameworks

JavaScript Tutorials

jQuery Tutorials