agyanadda@gmail.com

jQuery Examples

25 examples 25 you can try online 25 topics

Learn by doing. Every example below can be opened in our online editor — change the code, press Run and see the result instantly.

Open the Try it Now editor »

jQuery Introduction

jQuery Basics · 1 example
Example — Your first jQuery code HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<h2 id="title">Hello!</h2>
<p class="msg">Click the button to hide this paragraph.</p>
<button id="btn">Hide</button>

<script>
  $(function () {
    $('#btn').click(function () {
      $('.msg').hide();
      $('#title').text('jQuery did that!');
    });
  });
</script>

jQuery Get Started

jQuery Basics · 1 example
Example — jQuery starter page HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>jQuery Starter</title>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
  <h1>jQuery is ready?</h1>
  <p id="status">Checking...</p>

  <script>
    $(function () {
      $('#status').text('Yes! jQuery version ' + $.fn.jquery + ' is loaded.');
    });
  </script>
</body>
</html>

jQuery Syntax

jQuery Basics · 1 example
Example — One action, many elements HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<ul>
  <li>HTML</li>
  <li>CSS</li>
  <li>JavaScript</li>
</ul>
<p id="info"></p>
<button id="go">Style all items</button>

<script>
  $(function () {
    $('#info').text('Found ' + $('li').length + ' list items.');
    $('#go').click(function () {
      $('li').css({ color: 'white', background: '#1f386b', padding: '4px', margin: '2px' });
      $('#info').text('Changed: ' + $('li').first().text() + ' and the others');
    });
  });
</script>

jQuery Selectors

jQuery Basics · 1 example
Example — Selector playground HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<table border="1" cellpadding="6" style="border-collapse:collapse">
  <tr><td>Asha</td><td>88</td></tr>
  <tr><td>Ravi</td><td>64</td></tr>
  <tr><td>Neha</td><td>91</td></tr>
  <tr><td>Aman</td><td>27</td></tr>
</table>
<p><label><input type="checkbox" checked> HTML</label>
<label><input type="checkbox"> CSS</label>
<label><input type="checkbox" checked> jQuery</label></p>
<button id="stripe">Stripe rows</button>
<button id="count">Count checked</button>
<p id="out"></p>

<script>
  $(function () {
    $('#stripe').click(function () {
      $('tr:even').css('background', '#eef4ff');
      $('tr:last td').css('color', 'crimson');
    });
    $('#count').click(function () {
      $('#out').text($('input:checked').length + ' subjects selected');
    });
  });
</script>

jQuery Events

jQuery Basics · 1 example
Example — Click, hover and keyup HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<button id="like">👍 Like (0)</button>
<div id="box" style="width:180px;padding:20px;margin:12px 0;background:#eee">Hover over me</div>
<input id="search" placeholder="Type something">
<p>You typed: <strong id="typed"></strong></p>
<a href="https://www.agyanadda.com" id="link">This link is blocked</a>

<script>
  $(function () {
    let likes = 0;
    $('#like').on('click', function () {
      likes++;
      $(this).text('👍 Like (' + likes + ')');
    });

    $('#box').hover(
      function () { $(this).css('background', '#ffd43b').text('Mouse is in!'); },
      function () { $(this).css('background', '#eee').text('Hover over me'); }
    );

    $('#search').on('keyup', function () {
      $('#typed').text($(this).val());
    });

    $('#link').on('click', function (e) {
      e.preventDefault();
      alert('Default link action stopped.');
    });
  });
</script>

jQuery Hide and Show

jQuery Effects · 1 example
Example — Read more / read less HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<p>jQuery makes simple effects very easy.
  <span id="more" style="display:none">With one line you can hide, show or toggle any element, add speed and even run code after the effect ends.</span>
</p>
<button id="toggle">Read more</button>

<script>
  $(function () {
    $('#toggle').click(function () {
      const $btn = $(this);
      $('#more').toggle('fast', function () {
        $btn.text($('#more').is(':visible') ? 'Read less' : 'Read more');
      });
    });
  });
</script>

jQuery Fade

jQuery Effects · 1 example
Example — Auto-hiding notification HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<button id="save">Save profile</button>
<div id="toast" style="display:none;margin-top:10px;padding:10px 14px;background:#2b8a3e;color:#fff;border-radius:6px;width:max-content">✓ Profile saved</div>

<p style="margin-top:24px">
  <img id="pic" src="https://picsum.photos/id/1025/160/110" alt="Dog" style="border-radius:8px">
</p>
<button id="dim">Dim image</button>
<button id="full">Full image</button>

<script>
  $(function () {
    $('#save').click(function () {
      $('#toast').stop(true, true).fadeIn(300).delay(2000).fadeOut(600);
    });
    $('#dim').click(() => $('#pic').fadeTo('slow', 0.3));
    $('#full').click(() => $('#pic').fadeTo('slow', 1));
  });
</script>

jQuery Slide

jQuery Effects · 1 example
Example — FAQ accordion with slideToggle HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
  .question { background:#1f386b; color:#fff; padding:10px; margin-top:6px; cursor:pointer; border-radius:4px; }
  .answer { display:none; padding:10px; border:1px solid #ddd; border-top:none; }
</style>

<div class="question">Are AgyanAdda tutorials free?</div>
<div class="answer">Yes, every tutorial is free to read.</div>
<div class="question">Can I run the examples?</div>
<div class="answer">Yes, click "Try it Now" under any example.</div>
<div class="question">Do you have live classes?</div>
<div class="answer">Yes, see the Online Training page.</div>

<script>
  $(function () {
    $('.question').click(function () {
      const $answer = $(this).next('.answer');
      $('.answer').not($answer).slideUp();
      $answer.slideToggle();
    });
  });
</script>

jQuery Animate

jQuery Effects · 1 example
Example — Moving box and scroll to top HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<button id="run">Run animation</button>
<button id="step">Move +50px</button>
<button id="reset">Reset</button>
<div style="position:relative;height:120px;margin-top:10px">
  <div id="box" style="position:absolute;left:0;top:10px;width:80px;height:80px;background:#4a90e2;border-radius:8px"></div>
</div>
<div style="height:600px">Scroll down...</div>
<button id="top">⬆ Back to top</button>

<script>
  $(function () {
    const $box = $('#box');
    $('#run').click(function () {
      $box.stop(true)
        .animate({ left: '200px' }, 600)
        .animate({ width: '140px', opacity: 0.6 }, 400)
        .animate({ left: '0px', width: '80px', opacity: 1 }, 600);
    });
    $('#step').click(() => $box.animate({ left: '+=50px' }, 300));
    $('#reset').click(() => $box.stop(true).css({ left: 0, width: 80, opacity: 1 }));
    $('#top').click(() => $('html, body').animate({ scrollTop: 0 }, 500));
  });
</script>

jQuery Chaining and Callbacks

jQuery Effects · 1 example
Example — Chaining and callback HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<button id="go">Send message</button>
<p id="status" style="display:none;padding:8px"></p>
<div id="card" style="margin-top:10px;padding:14px;background:#fff3cd;width:220px">Click the card to remove it</div>

<script>
  $(function () {
    $('#go').click(function () {
      $('#status')
        .stop(true, true)
        .text('Message sent ✓')
        .css({ background: '#d3f9d8', color: '#2b8a3e' })
        .slideDown(300)
        .delay(1500)
        .slideUp(300);
    });

    $('#card').click(function () {
      $(this).fadeOut(500, function () {
        $(this).remove();
        alert('Card removed after the fade finished.');
      });
    });
  });
</script>

jQuery Get and Set Content

jQuery HTML and CSS · 1 example
Example — Live profile preview HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<input id="name" placeholder="Your name">
<select id="course">
  <option value="html">HTML</option>
  <option value="css">CSS</option>
  <option value="jquery" selected>jQuery</option>
</select>
<label><input type="checkbox" id="agree"> I agree</label>
<button id="submit" disabled>Submit</button>

<div style="margin-top:14px;padding:12px;border:1px solid #ddd;width:280px">
  <h3 id="pName">Guest</h3>
  <p>Course: <span id="pCourse"></span></p>
  <a id="pLink" href="#">Open tutorial</a>
</div>

<script>
  $(function () {
    function update() {
      $('#pName').text($('#name').val() || 'Guest');
      const course = $('#course').val();
      $('#pCourse').text($('#course option:selected').text());
      $('#pLink').attr('href', 'https://www.agyanadda.com/' + course);
    }
    $('#name, #course').on('input change', update);
    $('#agree').on('change', function () {
      $('#submit').prop('disabled', !$(this).prop('checked'));
    });
    update();
  });
</script>

jQuery Add and Remove Elements

jQuery HTML and CSS · 1 example
Example — Dynamic to-do list HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>li{margin:4px 0} .del{margin-left:8px;color:crimson;cursor:pointer;border:none;background:none}</style>

<input id="task" placeholder="New task">
<button id="addEnd">Add to end</button>
<button id="addTop">Add to top</button>
<button id="clear">Clear all</button>
<ul id="list"><li>Learn jQuery selectors<button class="del">✕</button></li></ul>

<script>
  $(function () {
    function makeItem() {
      const text = $.trim($('#task').val());
      if (!text) return null;
      $('#task').val('').focus();
      return $('<li>').text(text).append($('<button class="del">✕</button>'));
    }
    $('#addEnd').click(() => { const $li = makeItem(); if ($li) $('#list').append($li); });
    $('#addTop').click(() => { const $li = makeItem(); if ($li) $('#list').prepend($li); });
    $('#clear').click(() => $('#list').empty());
    $('#list').on('click', '.del', function () {
      $(this).parent().fadeOut(200, function () { $(this).remove(); });
    });
  });
</script>

The delete buttons use event delegation (.on with a selector), so new items work too.

jQuery CSS Classes

jQuery HTML and CSS · 1 example
Example — Active menu and dark mode HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
  body { transition: background .3s, color .3s; font-family: Arial, sans-serif; }
  body.dark { background: #1e1e1e; color: #eee; }
  .menu a { display:inline-block; padding:8px 14px; text-decoration:none; color:inherit; border-radius:6px; }
  .menu a.active { background:#1f386b; color:#fff; }
</style>

<nav class="menu">
  <a href="#" class="active">Home</a>
  <a href="#">Tutorials</a>
  <a href="#">Exams</a>
</nav>
<p><button id="theme">🌙 Dark mode</button></p>

<script>
  $(function () {
    $('.menu a').click(function (e) {
      e.preventDefault();
      $('.menu a').removeClass('active');
      $(this).addClass('active');
    });
    $('#theme').click(function () {
      $('body').toggleClass('dark');
      $(this).text($('body').hasClass('dark') ? '☀️ Light mode' : '🌙 Dark mode');
    });
  });
</script>

jQuery css() and Dimensions

jQuery HTML and CSS · 1 example
Example — Size information and scroll progress HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<div id="bar" style="position:fixed;top:0;left:0;height:5px;width:0;background:#e8590c;z-index:10"></div>
<div id="box" style="width:200px;padding:15px;border:5px solid #1f386b;margin:20px">Box</div>
<button id="info">Show sizes</button>
<button id="grow">Make wider</button>
<pre id="out"></pre>
<div style="height:900px">Scroll down to see the progress bar at the top.</div>

<script>
  $(function () {
    $('#info').click(function () {
      const $b = $('#box');
      $('#out').text([
        'width(): ' + $b.width(),
        'innerWidth(): ' + $b.innerWidth(),
        'outerWidth(): ' + $b.outerWidth(),
        'outerWidth(true): ' + $b.outerWidth(true),
        'offset top: ' + Math.round($b.offset().top)
      ].join('\n'));
    });
    $('#grow').click(() => $('#box').css({ width: '+=40', background: '#e7f1ff' }));
    $(window).on('scroll', function () {
      const max = $(document).height() - $(window).height();
      $('#bar').css('width', ($(this).scrollTop() / max * 100) + '%');
    });
  });
</script>

jQuery Traversing

jQuery HTML and CSS · 1 example
Example — Product cards with closest() and find() HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
  .product{display:inline-block;width:150px;border:1px solid #ddd;padding:10px;margin:5px;border-radius:8px;vertical-align:top}
  .product.added{border-color:#2b8a3e;background:#ebfbee}
</style>

<div class="product"><h4 class="name">Pen Drive</h4><p>₹<span class="price">499</span></p><button class="add">Add to cart</button></div>
<div class="product"><h4 class="name">Mouse</h4><p>₹<span class="price">349</span></p><button class="add">Add to cart</button></div>
<div class="product"><h4 class="name">Keyboard</h4><p>₹<span class="price">899</span></p><button class="add">Add to cart</button></div>
<h3>Cart total: ₹<span id="total">0</span></h3>
<ul id="cart"></ul>

<script>
  $(function () {
    let total = 0;
    $('.add').click(function () {
      const $card = $(this).closest('.product');
      const name = $card.find('.name').text();
      const price = Number($card.find('.price').text());
      total += price;
      $card.addClass('added').siblings().removeClass('added');
      $('#cart').append($('<li>').text(name + ' – ₹' + price));
      $('#total').text(total);
      $(this).text('Added ✓').prop('disabled', true);
    });
  });
</script>

jQuery each() and data()

jQuery HTML and CSS · 1 example
Example — Total with each() and data() HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<ul>
  <li class="course" data-id="1" data-fee="999">HTML Course</li>
  <li class="course" data-id="2" data-fee="1499">CSS Course</li>
  <li class="course" data-id="3" data-fee="2499">jQuery Course</li>
</ul>
<button id="calc">Calculate total fee</button>
<pre id="out"></pre>

<script>
  $(function () {
    $('#calc').click(function () {
      let total = 0;
      let lines = [];
      $('.course').each(function (i) {
        const fee = $(this).data('fee');
        total += fee;
        lines.push((i + 1) + '. ' + $(this).text() + ' (id ' + $(this).data('id') + '): ₹' + fee);
      });
      lines.push('Total: ₹' + total.toLocaleString('en-IN'));

      const skills = { level: 'Beginner', mode: 'Online' };
      $.each(skills, function (key, value) { lines.push(key + ' → ' + value); });

      $('#out').text(lines.join('\n'));
    });
  });
</script>

jQuery Form Handling

jQuery Forms · 1 example
Example — Validated sign-up form HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
  input, select { display:block; margin-top:6px; padding:6px; width:240px; }
  .error { border:2px solid crimson; }
  .msg { color:crimson; font-size:13px; }
</style>

<form id="signup" novalidate>
  <input name="name" id="name" placeholder="Full name"><span class="msg"></span>
  <input name="mobile" id="mobile" placeholder="Mobile"><span class="msg"></span>
  <select name="city" id="city"><option value="">Select city</option><option>Gaya</option><option>Patna</option></select><span class="msg"></span>
  <label style="display:block;margin-top:8px"><input type="checkbox" name="agree" id="agree" style="display:inline;width:auto"> I agree to the terms</label><span class="msg"></span>
  <button style="margin-top:10px">Sign up</button>
</form>
<pre id="out"></pre>

<script>
  $(function () {
    function check($field, ok, message) {
      $field.toggleClass('error', !ok);
      $field.nextAll('.msg').first().text(ok ? '' : message);
      return ok;
    }
    $('#signup').on('submit', function (e) {
      e.preventDefault();
      let valid = true;
      valid = check($('#name'), $.trim($('#name').val()).length >= 3, 'Enter at least 3 letters') && valid;
      valid = check($('#mobile'), /^[6-9]\d{9}$/.test($('#mobile').val()), 'Enter a 10-digit mobile number') && valid;
      valid = check($('#city'), $('#city').val() !== '', 'Please choose a city') && valid;
      valid = check($('#agree').parent(), $('#agree').is(':checked'), 'Please accept the terms') && valid;
      $('#out').text(valid ? 'Valid! Data: ' + $(this).serialize() : '');
    });
  });
</script>

jQuery Event Delegation

jQuery Forms · 1 example
Example — Editable student table HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>td,th{border:1px solid #ccc;padding:6px} table{border-collapse:collapse;margin-top:10px} tr.done{background:#ebfbee}</style>

<input id="student" placeholder="Student name">
<button id="add">Add student</button>
<table id="table">
  <tr><th>Name</th><th>Action</th></tr>
  <tr><td>Asha</td><td><button class="mark">Present</button> <button class="delete">Delete</button></td></tr>
</table>
<p>Present: <span id="count">0</span></p>

<script>
  $(function () {
    $('#add').click(function () {
      const name = $.trim($('#student').val());
      if (!name) return;
      const $row = $('<tr>').append($('<td>').text(name))
        .append('<td><button class="mark">Present</button> <button class="delete">Delete</button></td>');
      $('#table').append($row);
      $('#student').val('');
    });

    $('#table').on('click', '.mark', function () {
      $(this).closest('tr').toggleClass('done');
      $('#count').text($('#table tr.done').length);
    });

    $('#table').on('click', '.delete', function () {
      $(this).closest('tr').remove();
      $('#count').text($('#table tr.done').length);
    });

    $('#student').on('keyup', function (e) {
      if (e.key === 'Enter') $('#add').trigger('click');
    });
  });
</script>

Add new students — their buttons work because the events are delegated to #table.

jQuery AJAX Introduction

jQuery AJAX · 1 example
Example — Load JSON without reloading HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<button id="load">Load a random post</button>
<div id="post" style="margin-top:10px;padding:12px;border:1px solid #ddd;max-width:420px">Click the button.</div>

<script>
  $(function () {
    $('#load').click(function () {
      const id = Math.floor(Math.random() * 100) + 1;
      $('#post').text('Loading...');
      $.getJSON('https://jsonplaceholder.typicode.com/posts/' + id)
        .done(function (data) {
          $('#post').empty()
            .append($('<h4>').text('#' + data.id + ' ' + data.title))
            .append($('<p>').text(data.body));
        })
        .fail(function () {
          $('#post').text('Could not load the post. Check your internet connection.');
        });
    });
  });
</script>

Uses the free JSONPlaceholder test API.

jQuery get() and post()

jQuery AJAX · 1 example
Example — POST a form with jQuery HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<form id="comment">
  <input name="title" placeholder="Title" required><br><br>
  <textarea name="body" placeholder="Comment" rows="3" required></textarea><br>
  <button>Post comment</button>
</form>
<p id="msg"></p>

<script>
  $(function () {
    $('#comment').on('submit', function (e) {
      e.preventDefault();
      const $btn = $(this).find('button').prop('disabled', true).text('Posting...');
      $.post('https://jsonplaceholder.typicode.com/posts', $(this).serialize())
        .done(function (res) {
          $('#msg').css('color', 'green').text('Saved! Server gave it id ' + res.id + '.');
          $('#comment')[0].reset();
        })
        .fail(function (xhr) {
          $('#msg').css('color', 'crimson').text('Error ' + xhr.status + '. Please try again.');
        })
        .always(function () {
          $btn.prop('disabled', false).text('Post comment');
        });
    });
  });
</script>

JSONPlaceholder pretends to save the data and returns a new id.

jQuery $.ajax() Method

jQuery AJAX · 1 example
Example — Live search with $.ajax HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<input id="q" placeholder="Search users (try 'le')" style="padding:6px;width:260px">
<span id="loader" style="display:none">⏳</span>
<ul id="results"></ul>

<script>
  $(function () {
    let users = null;
    let timer;

    function render(term) {
      const list = users.filter(u => u.name.toLowerCase().includes(term));
      $('#results').empty();
      $.each(list, function (i, u) {
        $('#results').append($('<li>').text(u.name + ' – ' + u.email));
      });
      if (!list.length) $('#results').append('<li>No match</li>');
    }

    $('#q').on('input', function () {
      const term = $.trim($(this).val()).toLowerCase();
      clearTimeout(timer);
      timer = setTimeout(function () {
        if (users) return render(term);
        $.ajax({
          url: 'https://jsonplaceholder.typicode.com/users',
          method: 'GET',
          dataType: 'json',
          timeout: 8000,
          beforeSend: () => $('#loader').show()
        })
          .done(data => { users = data; render(term); })
          .fail(() => $('#results').html('<li>Could not load users.</li>'))
          .always(() => $('#loader').hide());
      }, 300);
    });
  });
</script>

A 300 ms wait (debounce) avoids sending a request on every key press.

jQuery Plugins

jQuery Projects and Best Practices · 1 example
Example — A simple character-counter plugin HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<textarea id="bio" rows="3" cols="40" placeholder="Short bio"></textarea>
<br><br>
<input id="title" size="40" placeholder="Post title">

<script>
  $.fn.charCounter = function (options) {
    const settings = $.extend({ max: 100, warnAt: 0.8 }, options);
    return this.each(function () {
      const $field = $(this).attr('maxlength', settings.max);
      const $count = $('<div>').css({ fontSize: '13px', color: '#666' });
      $field.after($count);
      function update() {
        const len = $field.val().length;
        $count.text(len + ' / ' + settings.max)
          .css('color', len >= settings.max * settings.warnAt ? 'crimson' : '#666');
      }
      $field.on('input', update);
      update();
    });
  };

  $(function () {
    $('#bio').charCounter({ max: 150 });
    $('#title').charCounter({ max: 60, warnAt: 0.9 });
  });
</script>

jQuery Mini Projects

jQuery Projects and Best Practices · 1 example
Example — Tabs, modal and gallery HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
  body{font-family:Arial,sans-serif}
  .tabs button{padding:8px 14px;border:none;background:#eee;cursor:pointer}
  .tabs button.active{background:#1f386b;color:#fff}
  .panel{display:none;padding:12px;border:1px solid #ddd}
  .panel.active{display:block}
  #modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:20}
  #modal .box{background:#fff;max-width:420px;margin:12vh auto;padding:16px;border-radius:8px;text-align:center}
  #modal img{max-width:100%;border-radius:6px}
  .thumbs img{width:90px;height:60px;object-fit:cover;margin:4px;cursor:pointer;border-radius:4px}
</style>

<div class="tabs">
  <button class="active" data-tab="about">About</button>
  <button data-tab="gallery">Gallery</button>
</div>
<div class="panel active" id="about">This mini project uses tabs, a modal and a gallery.</div>
<div class="panel" id="gallery">
  <div class="thumbs">
    <img src="https://picsum.photos/id/1015/600/400" alt="River">
    <img src="https://picsum.photos/id/1016/600/400" alt="Canyon">
    <img src="https://picsum.photos/id/1019/600/400" alt="Sea">
  </div>
</div>

<div id="modal"><div class="box"><img id="big" alt=""><p id="caption"></p><button id="close">Close</button></div></div>

<script>
  $(function () {
    $('.tabs').on('click', 'button', function () {
      $(this).addClass('active').siblings().removeClass('active');
      $('.panel').removeClass('active');
      $('#' + $(this).data('tab')).addClass('active');
    });

    $('.thumbs').on('click', 'img', function () {
      $('#big').attr({ src: $(this).attr('src'), alt: $(this).attr('alt') });
      $('#caption').text($(this).attr('alt'));
      $('#modal').fadeIn(200);
    });

    function closeModal() { $('#modal').fadeOut(200); }
    $('#close').on('click', closeModal);
    $('#modal').on('click', function (e) { if (e.target === this) closeModal(); });
    $(document).on('keydown', function (e) { if (e.key === 'Escape') closeModal(); });
  });
</script>

jQuery vs JavaScript

jQuery Projects and Best Practices · 1 example
Example — Same feature, two ways HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>.on{background:#1f386b;color:#fff}</style>

<button id="jq">jQuery button</button>
<button id="js">JavaScript button</button>
<p id="out"></p>

<script>
  // jQuery version
  $(function () {
    $('#jq').on('click', function () {
      $(this).toggleClass('on');
      $('#out').text('Toggled with jQuery');
    });
  });

  // Vanilla JavaScript version
  document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('js').addEventListener('click', function () {
      this.classList.toggle('on');
      document.getElementById('out').textContent = 'Toggled with vanilla JavaScript';
    });
  });
</script>

jQuery Best Practices

jQuery Projects and Best Practices · 1 example
Example — Clean jQuery pattern HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<input id="filter" placeholder="Filter courses">
<ul id="courses"></ul>

<script>
  jQuery(function ($) {
    // cache selectors once
    const $list = $('#courses');
    const $filter = $('#filter');
    const courses = ['HTML', 'CSS', 'Bootstrap', 'Tailwind CSS', 'JavaScript', 'jQuery', 'PHP', 'Laravel'];

    // build HTML once, append once
    function render(term) {
      const items = courses
        .filter(c => c.toLowerCase().includes(term))
        .map(c => $('<li>').text(c));
      $list.empty().append(items.length ? items : $('<li>').text('No course found'));
    }

    // debounce the input event
    let timer;
    $filter.on('input', function () {
      clearTimeout(timer);
      const term = $.trim($(this).val()).toLowerCase();
      timer = setTimeout(() => render(term), 200);
    });

    render('');
  });
</script>