back to course
Lesson 05 / 876%· free preview
Introduction5/6
Your First jQuery Program
A full runnable example — button + click handler + DOM update.
Definition
Your first jQuery program brings together everything: a <script> tag that loads the library, a $(function) handler that fires when the DOM is ready, a selector that picks a button, and an event handler that updates the page when the button is clicked. Five lines of code — a complete interactive feature.
The Full Program
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Hello jQuery</title> </head> <body> <h1>Hello jQuery</h1> <button id="hi">Say hi</button> <p id="out"></p> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script> $(function () { // 1. DOM ready $('#hi').on('click', function () { // 2. bind click $('#out') // 3. select output .text('Hello from jQuery!') // 4. change text .css('color', 'crimson'); // 5. chain a css change }); }); </script> </body> </html>
Walkthrough
$(function () { ... })— the safe way to run code once the DOM has parsed. Same as the old$(document).ready(...).$('#hi').on('click', ...)— find the button, bind a click handler.$('#out').text('Hello from jQuery!')— find the<p>and set its text (escaped, safe from XSS)..css('color', 'crimson')— chain a styling change onto the same jQuery object.
Try It Yourself
Save the snippet as index.html and double-click to open it in Chrome. Click Say hi. The paragraph should update and turn crimson.
Key Takeaways
- Every jQuery program starts with a
<script>tag that loads the library. - Wrap your code in
$(function(){ ... })so the DOM is parsed before you touch it. - The pattern is always: select → act —
$(selector).action(args). - Chain multiple actions on the same selection — no need to re-query.
- You can ship this whole thing as a single HTML file — no build step required.
Interview Questions
Practice Questions
- Extend the example: show an incrementing click count instead of a fixed message.
- Add a second button that resets the paragraph. Use
.text(''). - Move the
<script>block to the<head>without the ready wrapper — what breaks, and why?
Pro Tips
- Stick to one jQuery version per page; loading two silently breaks plugins.
- Put your own scripts AFTER the jQuery
<script>tag — never before. - Use
data-testidattributes alongside ids for stable automated tests.
AI-powered recap
Quick recap quiz?
We'll generate 5 MCQs from this lesson and check your understanding instantly. Takes ~30 seconds.
Ready to move on?
// example library
Want more hands-on snippets in jQuery?
Browse 1 runnable example · across 1 chapter · short, copy-paste-friendly · grouped by topic
// sharpen your skills
Put this into practice right now
LeetCode-style problems, graded difficulty, hints and expected outputs — learning beats passively reading every time.
// feedback.matters()
Did this lesson help you?
