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: 9DOM 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 accessorselectoris a CSS-style selectoraction()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
| Feature | Vanilla JavaScript | jQuery |
|---|---|---|
| Syntax | More verbose | Concise, chainable |
| Browser Compatibility | Varies by feature | Mostly handled automatically |
| Selecting Elements | document.querySelector() | $() selector |
| Event Handling | addEventListener() | .on() or event shortcuts |
| Animation | Requires custom code | Built-in methods |
| AJAX | fetch() 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:
- Maintaining existing websites and applications
- Rapid prototyping
- Building simple sites quickly
- Understanding core concepts that influenced modern frameworks
JavaScript Tutorials
- Create Interactive HTML Forms with CSS and JavaScript
- Create a Registration Form with HTML, CSS, and JavaScript
- Expandable Table with Collapsible Rows Using HTML, CSS, and JavaScript
- Call a JavaScript Function When a Checkbox is Checked or Unchecked
- JavaScript Examples [51 Useful Examples]
jQuery Tutorials
- Check if a Checkbox is Checked Using jQuery
- Handle Dropdown Change Event in jQuery
- Execute Functions After Page Load Using jQuery
- Check Which Radio Button is Selected Using jQuery
- 51 jQuery Examples with Source Code
- How to Check if Input is Empty Using jQuery
- jQuery Check if Array is Empty
- jQuery Check if String Contains Specific Word
- How to Check if jQuery is Loaded
- jQuery Check if String Contains: String Validation
- jQuery Check If ID Exists: Examples
- jQuery Check if Element is Visible
- jQuery Check if Element Has Class
- How to Check if an Element Exists in jQuery
- jQuery Set Hidden Field Value
- jQuery Validate Form Before Submit
- jQuery Disable Button After Click: With Examples
- jQuery Replace Text in String
- jQuery Drag and Drop File Upload
- jQuery Get ID of Clicked Element
- jQuery Remove All Options from Select
- jQuery Set Selected Option by Text
- jQuery Remove Element by ID: with Examples
- How to Set Selected Value of Dropdown in jQuery?
- How to Get URL Parameters Using jQuery?
- How to Add Options to Select Dropdown Using jQuery?
- jQuery Wait for Function to Finish
- jQuery Open Link in New Tab
- jQuery Set Focus on Element
- How to Get the Value of a Textarea in jQuery
- jQuery Hide Element by ID
- How to Convert String to Number in jQuery
- How to Check jQuery Version
- jQuery “$ is not a function” Error
- jQuery Get Text of Selected Option
- JavaScript vs jQuery: Key Differences
- How to Fix “jQuery $ is not defined” Error
- How to Set Radio Button Checked in jQuery
- jQuery Get Selected Radio Button Value
- jQuery Wait for Element to Exist
- jQuery addClass() Method
- jQuery Find Next Element with Class
- How to Get the ID of an Element Using jQuery
- jQuery Get Value of Input
- Set Current Date In Datepicker Using JavaScript Or jQuery