top of page

Learn through our Blogs, Get Expert Help, Mentorship & Freelance Support!

Welcome to Colabcodes, where innovation drives technology forward. Explore the latest trends, practical programming tutorials, and in-depth insights across software development, AI, ML, NLP and more. Connect with our experienced freelancers and mentors for personalised guidance and support tailored to your needs.

Coding expert help blog - colabcodes

Learn jQuery from Scratch: Fundamentals, Syntax, and Core Concepts

  • Writer: Samul Black
    Samul Black
  • Jul 25
  • 8 min read

jQuery remains a powerful tool for simplifying JavaScript and enhancing interactivity in web development. In this blog, we’ll explore jQuery from the ground up — covering its core fundamentals, intuitive syntax, and essential concepts like DOM manipulation, event handling, and animations. By the end, you'll have a solid grasp of how to use jQuery effectively in modern web projects.

Tutorial for jQuery from Scratch - Colabcodes

What is jQuery?

jQuery is a fast, lightweight, and feature-rich JavaScript library designed to simplify HTML document traversal, event handling, animation, and AJAX interactions. Originally released in 2006 by John Resig, jQuery quickly became a staple in front-end development due to its elegant syntax and ability to streamline repetitive coding tasks.

At its core, jQuery abstracts away much of the complexity inherent in native JavaScript, particularly when dealing with the DOM and handling browser inconsistencies — a common pain point in the mid-2000s. Its chainable syntax allows developers to perform multiple operations on elements with minimal code, while its extensive API provides a rich toolkit for building dynamic and responsive user interfaces.


Why jQuery Became So Popular

During the early days of web development, interacting with the DOM (Document Object Model) using vanilla JavaScript was verbose and often inconsistent across different browsers. jQuery offered a welcome abstraction, wrapping complex JavaScript operations in clean, cross-browser-compatible methods. Its slogan — “Write less, do more” — perfectly captured its ethos and appeal to developers.

With an intuitive syntax and a vibrant plugin ecosystem, jQuery enabled developers to build dynamic, interactive websites rapidly, without needing to reinvent the wheel.


jQuery’s Relevance in Modern Web Development

While modern frameworks like React, Vue, and Angular have taken the spotlight in recent years, jQuery still holds relevance — particularly in legacy systems, rapid prototyping, and simpler projects that don’t necessitate a full-fledged SPA (Single Page Application) architecture. It’s also widely used in CMS platforms like WordPress and Magento, making it an essential skill for working with pre-built themes and plugins.

For beginners, learning jQuery serves as an excellent stepping stone — bridging the gap between raw JavaScript and more advanced front-end frameworks.


jQuery vs Vanilla JavaScript: A Quick Comparison

To better appreciate jQuery’s convenience, consider the following task: hiding a div with the ID #message.


Using vanilla JavaScript:

document.getElementById("message").style.display = "none";

Using jQuery:

$("#message").hide();

As evident, jQuery reduces verbosity, handles cross-browser quirks behind the scenes, and encourages a more expressive coding style. It abstracts away the clutter, letting developers focus on functionality rather than compatibility nuances.


Setting Up jQuery

Before diving into jQuery’s syntax and capabilities, you’ll need to set it up in your development environment. Fortunately, jQuery is incredibly easy to include — it doesn’t require any complex configuration or build tools to get started.


Method 1: Using a CDN (Content Delivery Network)

The quickest and most recommended way to include jQuery in a web project is by linking it via a CDN. This approach leverages cached versions of the library from trusted servers, improving load times and reducing bandwidth usage.

Here’s how you can include the latest version of jQuery via CDN:

<!DOCTYPE html>
<html>
<head>
  <title>My jQuery Project</title>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
  <h1>Hello jQuery!</h1>
</body>
</html>

Simply place the <script> tag within the <head> or just before the closing </body> tag. The latter ensures that the DOM is loaded before jQuery executes any scripts interacting with it.

Tip: Always use the latest stable version to ensure optimal performance and security.

Method 2: Hosting jQuery Locally

If you prefer working offline or want more control over dependencies, you can download jQuery and reference it locally:


  1. Visit the official jQuery download page.

  2. Download the compressed production version (for performance) or the uncompressed development version (for readability).

  3. Place the .js file in your project directory, then link it:

<script src="js/jquery-3.7.1.min.js"></script>

Make sure the file path matches your folder structure.


Basic HTML Structure Using jQuery

Here’s a minimal boilerplate that includes jQuery and a small script block to confirm it’s working:

<!DOCTYPE html>
<html>
<head>
  <title>jQuery Setup Test</title>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
  <button id="greet">Click Me</button>

  <script>
    $(document).ready(function() {
      $("#greet").click(function() {
        alert("jQuery is working!");
      });
    });
  </script>
</body>
</html>

This small script ensures your jQuery is functional — it waits for the DOM to load, then attaches a click event to the button. A snippet of it is shown below:

hello world for jQuery - colabcodes

jQuery Syntax Basics

jQuery's syntax is one of its greatest strengths — concise, expressive, and easy to grasp. Even with minimal JavaScript experience, you can start writing powerful code in just a few lines.


General Syntax Format

At its core, jQuery follows a simple and memorable pattern:

$(selector).action();

This line of code tells jQuery three things:


  1. Which element to target

  2. What to do with that element

  3. When to do it (usually triggered by an event)


Breaking It Down

Let’s break down each component of this syntax:


  • $: This is the jQuery function — a shorthand reference to the jQuery object itself. It’s used to access jQuery’s functionality.

  • selector: A string that identifies the HTML element(s) you want to manipulate. This works similarly to CSS selectors — such as "#id", ".class", or "element".

  • action(): A jQuery method that defines what you want to do — such as hide, show, change content, bind events, or modify styles.


DOM Manipulation with jQuery

One of the core strengths of jQuery is how effortlessly it allows you to manipulate the DOM (Document Object Model). Whether you're updating content, modifying attributes, or dynamically adding/removing elements — jQuery simplifies it all with clean, concise syntax.

1. Selecting Elements

Before any manipulation, you first need to select the target elements. jQuery uses CSS-style selectors, making it very intuitive.


Examples:

// Select by ID
$('#myElement')

// Select by class
$('.menu-item')

// Select all paragraphs
$('p')

// Select input elements of type text
$('input[type="text"]')
Tip: You can chain actions after selection, e.g., $('#box').hide().fadeIn();

2. Changing Content and Attributes

Once you’ve selected an element, changing its content or attributes is simple.


Change Text or HTML Content:

// Set plain text
$('#title').text('Welcome to jQuery!')

// Set HTML content
$('#content').html('<strong>This is bold text</strong>')

Modify Attributes:

// Change the href of a link
$('a#link').attr('href', 'https://colabcodes.com')

// Add a class
$('#box').addClass('highlight')

// Remove a class
$('#box').removeClass('highlight')

Adding & Removing Elements

jQuery makes it easy to dynamically create and remove elements from the DOM.


Add Elements:

// Append element inside another
$('#list').append('<li>New Item</li>')

// Prepend to the beginning
$('#list').prepend('<li>First Item</li>')

Remove or Empty Elements:

// Remove the element entirely
$('#ad-banner').remove()

// Remove all inner content but keep the element
$('#container').empty()

Real-World Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>jQuery DOM Manipulation</title>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    .message-box {
      font-size: 18px;
      font-weight: bold;
    }
  </style>
</head>
<body>

  <div id="user-msg"></div>
  <button id="updateBtn">Show Message</button>

  <script>
    $(document).ready(function() {
      $('#updateBtn').click(function() {
        $('#user-msg')
          .text('Hello, user!')
          .css('color', 'green')
          .addClass('message-box');
      });
    });
  </script>

</body>
</html>

Output:

simple example from jQuery - colabcodes








This simple example demonstrates

:

  • Element selection (#updateBtn)

  • Event binding (click)

  • Content update (.text())

  • CSS change (.css())

  • Class addition (.addClass())


Event Handling with jQuery

One of the standout features of jQuery is how effortlessly it handles user interactions. Events like click, hover, submit, and keydown can be easily bound to DOM elements, making your site dynamic and interactive with minimal code.


Common jQuery Events

jQuery provides shorthand methods for most frequently used events:

Event Type

jQuery Method

Description

Click

.click()

Fires when an element is clicked

Hover

.hover()

Fires when mouse enters and leaves an element

Submit

.submit()

Fires when a form is submitted

Change

.change()

Detects changes in inputs/select boxes

Keyup

.keyup()

Fires when a key is released

Mouseover

.mouseover()

Fires when the pointer enters an element


How jQuery Simplifies Event Binding

With plain JavaScript, you'd often have to loop through elements, attach listeners, and handle browser quirks. jQuery abstracts all of that into a clean syntax.


Example: Click Event

<button id="greet">Click Me</button>
<p id="message"></p>

<script>
  $(function() {
    $('#greet').click(function() {
      $('#message').text('Hello from jQuery!');
    });
  });
</script>

Example: Hover Event

<div id="box" style="width:100px; height:100px; background:gray;"></div>

<script>
  $(function() {
    $('#box').hover(
      function() {
        $(this).css('background', 'blue');
      },
      function() {
        $(this).css('background', 'gray');
      }
    );
  });
</script>

Preventing Default Behaviors

Some HTML elements have default browser behavior. For instance, links redirect and forms reload the page. jQuery lets you prevent these easily with .preventDefault().


Example: Prevent Form Submission

<form id="myForm">
  <input type="text" placeholder="Your name" />
  <button type="submit">Submit</button>
</form>

<script>
  $(function() {
    $('#myForm').submit(function(event) {
      event.preventDefault(); // Stop form from reloading page
      alert('Form submission prevented!');
    });
  });
</script>

Example: Prevent Link Redirect

<a href="https://google.com" id="externalLink">Go to Google</a>

<script>
  $(function() {
    $('#externalLink').click(function(event) {
      event.preventDefault();
      alert('Link click prevented.');
    });
  });
</script>

Effects and Animations in jQuery

jQuery comes with a built-in set of animation and effect functions that let you add interactivity without relying on CSS or external libraries. Whether you're hiding elements, sliding menus, or animating properties — jQuery makes it intuitive and chainable.


Basic Effects

Method

Description

.show()

Displays a hidden element

.hide()

Hides an element

.toggle()

Switches between showing and hiding

.fadeIn()

Fades in a hidden element

.fadeOut()

Fades out a visible element

.slideUp()

Slides an element up to hide it

.slideDown()

Slides an element down to show it

.slideToggle()

Toggles slide up/down

jQuery Chaining

One of jQuery’s best features is method chaining — a syntax pattern that lets you perform multiple operations on the same element in a single, readable line.

Instead of writing:

$("#box").css("color", "blue");
$("#box").slideUp(1000);
$("#box").slideDown(1000);

You can simply chain the methods:

$("#box").css("color", "blue").slideUp(1000).slideDown(1000);

This not only improves code readability but also slightly boosts performance by reducing repeated DOM queries.


Example: Chained Effects:

<button id="chainBtn">Start Animation</button>
<div id="chainBox" style="width:150px; height:100px; background:#444; color:white; text-align:center; line-height:100px;">Box</div>

<script>
  $(function() {
    $('#chainBtn').click(function() {
      $('#chainBox')
        .css("background", "#3498db")
        .slideUp(800)
        .slideDown(800)
        .fadeTo(600, 0.5)
        .fadeTo(600, 1);
    });
  });
</script>

Let's build a fully functional dropdown menu using all the jQuery techniques we've covered:


  • DOM selection

  • Event handling (click, hover)

  • Preventing default behavior

  • Show/hide and slide effects

  • Custom animations with .animate()

  • Method chaining


Final Output: jQuery-Powered Dropdown Menu

The dropdown will:


  • Toggle visibility on click.

  • Use slide animations.

  • Highlight hovered items.

  • Use method chaining for styling and effects.

  • Animate submenu appearance.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>jQuery Dropdown Menu</title>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 40px;
    }

    /* Navigation Styles */
    .dropdown {
      position: relative;
      display: inline-block;
    }

    .dropdown-btn {
      background-color: #3498db;
      color: white;
      padding: 12px 20px;
      border: none;
      cursor: pointer;
      font-size: 16px;
      border-radius: 4px;
    }

    .dropdown-menu {
      display: none;
      position: absolute;
      background-color: white;
      min-width: 160px;
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
      z-index: 1;
      margin-top: 5px;
      padding: 0;
      border-radius: 4px;
      overflow: hidden;
    }

    .dropdown-menu a {
      color: #333;
      padding: 12px 16px;
      display: block;
      text-decoration: none;
      transition: background 0.3s ease;
    }

    .dropdown-menu a:hover {
      background-color: #f1f1f1;
    }

    .highlighted {
      background-color: #e0f7fa !important;
    }
  </style>
</head>
<body>

  <h2>🔽 jQuery Dropdown Menu Demo</h2>

  <div class="dropdown">
    <button class="dropdown-btn">Menu</button>
    <div class="dropdown-menu">
      <a href="#">Home</a>
      <a href="#">Services</a>
      <a href="#">About Us</a>
      <a href="#">Contact</a>
    </div>
  </div>

  <script>
    $(function() {
      // Toggle dropdown with slide effect
      $('.dropdown-btn').click(function(e) {
        e.preventDefault(); // Prevent default button behavior

        $('.dropdown-menu')
          .stop(true, true) // Stop ongoing animation queue
          .slideToggle(400)
          .css('border', '1px solid #ccc')
          .animate({ opacity: 1 }, 200);
      });

      // Highlight item on hover with class toggle
      $('.dropdown-menu a').hover(
        function() {
          $(this).addClass('highlighted');
        },
        function() {
          $(this).removeClass('highlighted');
        }
      );

      // Optional: Close dropdown if clicked outside
      $(document).click(function(e) {
        if (!$(e.target).closest('.dropdown').length) {
          $('.dropdown-menu').slideUp(300);
        }
      });
    });
  </script>

</body>
</html>

Output:

Drop down menu using jQuery - colabcodes

Conclusion: Why jQuery Still Matters

In this tutorial, we covered the core features of jQuery — from selecting and manipulating DOM elements to handling events, creating animations, chaining methods, and building a functional dropdown menu. You’ve seen how jQuery simplifies common frontend tasks with clean and readable code.

While modern frameworks like React and Vue dominate today’s landscape, jQuery remains useful — especially for beginners, small projects, and legacy systems. It’s lightweight, easy to learn, and perfect for quickly adding interactivity without the need for complex setups.

If you’re maintaining older websites, working with platforms like WordPress, or just want to build fast and simple UI features, jQuery is still a great tool to have in your web development toolkit.

Get in touch for customized mentorship, research and freelance solutions tailored to your needs.

bottom of page