jQuery Top Codes

jQuery Accordion Example

An accordion shows a list of headings, and only one panel is open at a time. This code uses slideToggle() and slideUp().

HTML

<div class="accordion">
  <h3 class="acc-head">What is jQuery?</h3>
  <div class="acc-body" style="display:none">jQuery is a JavaScript library.</div>

  <h3 class="acc-head">Is it free?</h3>
  <div class="acc-body" style="display:none">Yes, it is free and open source.</div>

  <h3 class="acc-head">Which version to use?</h3>
  <div class="acc-body" style="display:none">The latest 3.x or 4.x version.</div>
</div>

CSS

.acc-head { cursor: pointer; background: #f1f1f1; padding: 10px; margin: 0; border-bottom: 1px solid #ddd; }
.acc-head.open { background: #dbeafe; }
.acc-body { padding: 10px; border: 1px solid #ddd; border-top: 0; }

jQuery code

$('.acc-head').on('click', function () {
  var $head = $(this);
  var $body = $head.next('.acc-body');

  $('.acc-head').not($head).removeClass('open');
  $('.acc-body').not($body).slideUp(200);

  $head.toggleClass('open');
  $body.slideToggle(200);
});

// test: open the 2nd item, then the 3rd
$('.acc-head').eq(1).click();
$('.acc-head').eq(2).click();
$('.acc-body').each(function (i) {
  console.log('Panel ' + (i + 1) + ': ' + $(this).css('display'));
});
Console output

Panel 1: none
Panel 2: none
Panel 3: block

How it works

  • .next('.acc-body') finds the panel that belongs to the clicked heading.
  • .not($body) selects all the other panels, and they are closed with slideUp().
  • toggleClass('open') changes the style of the active heading, and slideToggle() opens or closes the panel.
  • The test clicks the second and then the third heading. The output shows that only the third panel stays open.
Note: For a keyboard friendly accordion, use button elements inside the headings and add the aria-expanded attribute. See Fade and Slide Effects.

jQuery Tabs Example

Tabs show one content block at a time. The tab buttons and the content blocks are connected with a data attribute.

HTML

<div class="tabs">
  <button class="tab-btn active" data-target="#about">About</button>
  <button class="tab-btn" data-target="#course">Courses</button>
  <button class="tab-btn" data-target="#contact">Contact</button>

  <div id="about" class="tab-panel">About us text</div>
  <div id="course" class="tab-panel" style="display:none">Course list</div>
  <div id="contact" class="tab-panel" style="display:none">Contact details</div>
</div>

CSS

.tab-btn { padding: 8px 14px; border: 1px solid #ccc; background: #f5f5f5; cursor: pointer; }
.tab-btn.active { background: #fff; border-bottom-color: #fff; font-weight: bold; }
.tab-panel { border: 1px solid #ccc; padding: 12px; }

jQuery code

$('.tab-btn').on('click', function () {
  var $btn = $(this);

  $('.tab-btn').removeClass('active');
  $btn.addClass('active');

  $('.tab-panel').hide();
  $($btn.data('target')).fadeIn(150);
});

$('.tab-btn').eq(1).click();
$('.tab-panel').each(function () {
  console.log(this.id + ': ' + $(this).css('display'));
});
Console output

about: none
course: block
contact: none

How it works

  • The data-target attribute has the selector of the panel to show.
  • All panels are hidden first, and then only the chosen panel is shown with fadeIn().
  • The active class is moved to the clicked tab.
Note: You can also open a tab from the address (the hash) with location.hash. For a plain JavaScript version see the code JavaScript Tabs without jQuery.

jQuery Modal Popup Example

A modal is a box which opens over the page. This code opens it with a button and closes it with the close button, a click on the dark background, or the Escape key.

HTML

<button id="open-modal">Open popup</button>

<div id="overlay" class="overlay" style="display:none">
  <div class="modal">
    <button class="close" aria-label="Close">&times;</button>
    <h3>Hello!</h3>
    <p>This is a popup made with jQuery.</p>
  </div>
</div>

CSS

.overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,.6);
           display: flex; align-items: center; justify-content: center; }
.modal { background: #fff; padding: 20px; border-radius: 6px; min-width: 280px; position: relative; }
.close { position: absolute; top: 6px; right: 10px; border: 0; background: none; font-size: 22px; cursor: pointer; }

jQuery code

var $overlay = $('#overlay');

function openModal()  { $overlay.fadeIn(150).css('display', 'flex'); }
function closeModal() { $overlay.fadeOut(150); }

$('#open-modal').on('click', openModal);
$('.close').on('click', closeModal);

// click on the dark background, but not inside the box
$overlay.on('click', function (e) {
  if (e.target === this) closeModal();
});

// Escape key
$(document).on('keyup', function (e) {
  if (e.key === 'Escape') closeModal();
});

// test
$('#open-modal').click();
console.log('after open:   ' + $overlay.css('display'));
$(document).trigger($.Event('keyup', { key: 'Escape' }));
console.log('after Escape: ' + $overlay.css('display'));
Console output

after open: flex
after Escape: none

How it works

  • e.target === this checks that the click was on the overlay itself, and not on the box inside it.
  • The keyup event on the document handles the Escape key.
  • The overlay uses display: flex to center the box, so we set the display to flex after fadeIn().
Note: For a good popup also move the focus into it, keep the focus inside while it is open, and give it role="dialog" for screen readers. See jQuery Events.

jQuery Live Search Filter for a Table

This code filters the rows of a table while the user types. It checks all the cells of a row and ignores the upper and lower case.

HTML

<input type="text" id="table-search" placeholder="Search...">
<table id="students">
  <thead><tr><th>Name</th><th>City</th></tr></thead>
  <tbody>
    <tr><td>Anita Rao</td><td>Delhi</td></tr>
    <tr><td>Ravi Kumar</td><td>Pune</td></tr>
    <tr><td>Maya Singh</td><td>Delhi</td></tr>
    <tr><td>Manish Das</td><td>Kolkata</td></tr>
  </tbody>
</table>
<p id="no-result" style="display:none">No result found</p>

jQuery code

$('#table-search').on('input', function () {
  var term = $(this).val().toLowerCase().trim();
  var shown = 0;

  $('#students tbody tr').each(function () {
    var match = $(this).text().toLowerCase().indexOf(term) !== -1;
    $(this).toggle(match);
    if (match) shown++;
  });

  $('#no-result').toggle(shown === 0);
});

function search(text) {
  $('#table-search').val(text).trigger('input');
  console.log('"' + text + '": ' + $('#students tbody tr').filter(function () { return $(this).css('display') !== 'none'; }).length + ' row(s), message: ' + $('#no-result').css('display'));
}

search('delhi');
search('ma');
search('xyz');
search('');
Console output

"delhi": 2 row(s), message: none
"ma": 3 row(s), message: none
"xyz": 0 row(s), message: block
"": 4 row(s), message: none

How it works

  • $(this).text() of a row has the text of all its cells together, so we search in all columns.
  • .toggle(match) shows the row if it matches and hides it if not.
  • The message “No result found” is shown only when no row is visible.
  • The test function counts the rows which are not hidden.
Note: For a big table (thousands of rows), wait a short time after the last key before you filter, or filter on the server. See jQuery each().

jQuery Form Validation Example

This code checks a registration form before it is sent. It shows an error below each wrong field, and stops the submit when there is an error.

HTML

<form id="register" novalidate>
  <p><input type="text" name="name" placeholder="Name"> <span class="err"></span></p>
  <p><input type="text" name="email" placeholder="Email"> <span class="err"></span></p>
  <p><input type="password" name="password" placeholder="Password"> <span class="err"></span></p>
  <button type="submit">Register</button>
</form>

CSS

.err { color: #c00; font-size: 13px; }
input.invalid { border: 1px solid #c00; }

jQuery code

function validate(name, value) {
  value = value.trim();
  if (name === 'name' && value === '') return 'Name is required';
  if (name === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return 'Enter a valid email';
  if (name === 'password' && value.length < 6) return 'Password needs 6 or more characters';
  return '';
}

$('#register').on('submit', function (e) {
  var ok = true;

  $(this).find('input').each(function () {
    var message = validate(this.name, this.value);
    $(this).toggleClass('invalid', message !== '');
    $(this).next('.err').text(message);
    if (message) ok = false;
  });

  if (!ok) e.preventDefault();
  console.log('form valid: ' + ok);
});

// test 1: empty form
$('#register').trigger('submit');
console.log($('.err').map(function () { return $(this).text(); }).get());

// test 2: correct data
$('[name=name]').val('Anita');
$('[name=email]').val('anita@example.com');
$('[name=password]').val('secret123');
$('#register').trigger('submit');
Console output

form valid: false
[ 'Name is required', 'Enter a valid email', 'Password needs 6 or more characters' ]
form valid: true

How it works

  • The validate() function returns an error text, or an empty text if the value is fine.
  • toggleClass('invalid', message !== '') adds the red border only for wrong fields.
  • e.preventDefault() stops the form if any field has an error.
  • The email check is a simple pattern. The final check must be done on the server too.
Note: Do not rely only on JavaScript validation. Always validate again on the server. See jQuery Forms.

jQuery Image Slider Example

A slider shows one slide at a time. This code has the Next and Previous buttons, and it goes round (after the last slide it shows the first one). Pictures are replaced by text boxes in the test.

HTML

<div id="slider">
  <div class="slide">Slide 1</div>
  <div class="slide" style="display:none">Slide 2</div>
  <div class="slide" style="display:none">Slide 3</div>
</div>
<button id="prev">Previous</button>
<button id="next">Next</button>

CSS

#slider { width: 400px; height: 200px; position: relative; overflow: hidden; }
.slide { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

jQuery code

var $slides = $('#slider .slide');
var current = 0;

function show(index) {
  $slides.eq(current).fadeOut(300);
  current = (index + $slides.length) % $slides.length;
  $slides.eq(current).fadeIn(300);
}

$('#next').on('click', function () { show(current + 1); });
$('#prev').on('click', function () { show(current - 1); });

// automatic change every 4 seconds (stop it with clearInterval)
var timer = setInterval(function () { show(current + 1); }, 4000);

// test
function state() {
  return $slides.map(function () { return $(this).css('display') === 'none' ? '-' : 'VISIBLE'; }).get().join(' ');
}
$('#next').click(); console.log('next:     ' + state());
$('#next').click(); console.log('next:     ' + state());
$('#next').click(); console.log('next:     ' + state() + '  (back to the first)');
$('#prev').click(); console.log('previous: ' + state() + '  (to the last)');
clearInterval(timer);
Console output

next: – VISIBLE –
next: – – VISIBLE
next: VISIBLE – – (back to the first)
previous: – – VISIBLE (to the last)

How it works

  • (index + length) % length makes the numbers go round in both directions.
  • The old slide fades out, and the new one fades in. The slides are placed on top of each other with CSS.
  • setInterval() changes the slide automatically. Stop it when the user clicks, or when the mouse is over the slider, for a better experience.
Note: For a real site also add a pause on hover, touch support and accessible buttons. See Fade and Slide Effects.