We are still cooking the magic in the way!
jQuery Syntax & Document Ready
Understanding jQuery Syntax
jQuery has a simple and consistent syntax that makes it easy to learn and use. In this lesson, we'll explore the fundamental syntax patterns and the crucial "document ready" function.
The Basic jQuery Syntax
All jQuery statements follow this pattern:
$(selector).action()
Let's break this down:
- $ - The jQuery symbol (alias for jQuery)
- selector - Finds HTML elements (like CSS selectors)
- action() - The method to perform on the element(s)
Real Examples
// Hide all paragraphs
$('p').hide();
// Change text of element with id="title"
$('#title').text('New Title');
// Add a class to all links
$('a').addClass('highlight');
// Get the value of an input field
var name = $('#username').val();
$('p').hide()(common)jQuery('p').hide()(full syntax)
The Document Ready Function
One of the most important concepts in jQuery is waiting for the page to load before running your code. This is called the "document ready" event.
Why Do We Need It?
JavaScript executes as soon as it's encountered. If you try to manipulate an element before it exists in the DOM, your code will fail!
<script>
$('#myButton').click(function() {
alert('Clicked!');
});
</script>
<button id="myButton">Click Me</button>
The Solution: Document Ready
The document ready function ensures your code runs only after the DOM is fully loaded:
$(document).ready(function() {
// Your jQuery code here
$('#myButton').click(function() {
alert('Clicked!');
});
});
Shorthand Syntax (Recommended):
$(function() {
// Your jQuery code here
$('#myButton').click(function() {
alert('Clicked!');
});
});
$(function() {...}) is the preferred and most common way to write document ready. It's shorter and cleaner!
Complete Example
<!DOCTYPE html>
<html>
<head>
<title>Document Ready Example</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function() {
// This code runs when DOM is ready
$('#showBtn').click(function() {
$('#message').show();
});
$('#hideBtn').click(function() {
$('#message').hide();
});
});
</script>
</head>
<body>
<button id="showBtn">Show Message</button>
<button id="hideBtn">Hide Message</button>
<p id="message" style="display:none;">Hello from jQuery!</p>
</body>
</html>
Document Ready vs Window Load
There's an important difference between document ready and window load:
// Document Ready - fires when DOM is ready
$(function() {
console.log('DOM is ready!');
// Images might still be loading
});
// Window Load - fires when everything is loaded
$(window).on('load', function() {
console.log('Everything including images loaded!');
});
| Event | When It Fires | Use Case |
|---|---|---|
| Document Ready | When DOM is parsed | Most jQuery code (faster) |
| Window Load | When all assets loaded | Image size calculations |
Multiple Document Ready Functions
You can have multiple document ready functions, and they'll all execute in order:
$(function() {
console.log('First ready function');
});
$(function() {
console.log('Second ready function');
});
$(function() {
console.log('Third ready function');
});
// Output:
// First ready function
// Second ready function
// Third ready function
This is useful when working with multiple JavaScript files or organizing code into modules.
External JavaScript Files
In production, you'll typically write jQuery in separate .js files:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<h1 id="heading">Welcome</h1>
<button id="changeBtn">Change Text</button>
</body>
</html>
js/main.js:
$(function() {
$('#changeBtn').click(function() {
$('#heading').text('Text Changed!');
});
});
Method Chaining
One of jQuery's most powerful features is method chaining - calling multiple methods on the same element:
// Without chaining (repetitive)
$('#box').css('color', 'red');
$('#box').fadeIn();
$('#box').addClass('highlight');
// With chaining (elegant!)
$('#box')
.css('color', 'red')
.fadeIn()
.addClass('highlight');
Chaining works because most jQuery methods return the jQuery object, allowing you to call another method immediately.
Common jQuery Methods Preview
Here are some methods you'll use frequently (we'll cover these in detail later):
// Text and HTML manipulation
$('#title').text('New Text');
$('#content').html('<strong>Bold Text</strong>');
// CSS manipulation
$('p').css('color', 'blue');
$('div').addClass('active');
// Show/Hide
$('#menu').show();
$('#popup').hide();
// Events
$('#btn').click(function() { /* ... */ });
$('#input').change(function() { /* ... */ });
// Effects
$('#box').fadeIn();
$('#box').slideUp();
Create an HTML page with:
- A heading with id="title"
- A paragraph with id="description"
- Three buttons: "Show", "Hide", and "Toggle"
Using document ready and jQuery, make the buttons control the visibility of the paragraph. Use method chaining where possible.
💡 Solution
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function() {
$('#showBtn').click(function() {
$('#description').fadeIn();
});
$('#hideBtn').click(function() {
$('#description').fadeOut();
});
$('#toggleBtn').click(function() {
$('#description').fadeToggle();
});
});
</script>
</head>
<body>
<h1 id="title">jQuery Practice</h1>
<p id="description">This is a description paragraph.</p>
<button id="showBtn">Show</button>
<button id="hideBtn">Hide</button>
<button id="toggleBtn">Toggle</button>
</body>
</html>
Debugging Tips
When your jQuery code doesn't work, check these common issues:
- jQuery not loaded - Check browser console for "$ is not defined"
- Wrong selector - Verify element IDs and classes match
- Code runs too early - Always use document ready
- Typos - JavaScript is case-sensitive ($("#myButton" vs $("#mybutton")
- Missing parentheses - Remember:
.show()not.show
Summary
In this lesson, you learned:
- jQuery syntax follows the pattern:
$(selector).action() - $ is a shortcut for jQuery
- Document ready ensures DOM is loaded before code runs
- Use
$(function() {...})as the shorthand for document ready - Method chaining allows multiple actions on the same element
- Always load jQuery before your custom scripts
In the next lesson, we'll explore jQuery selectors in depth!