Tutorial jQuery - nvbach91/4IZ268-2022-2023-ZS GitHub Wiki

  • start
$(document).ready(() => {
  // initialize app
  // start scripting
  const someLocalVariable;
});
  • select, create, insert
// selecting elements matching a CSS selector
const selectedElement = $('#my-element');       // returns a jQuery collection of elements
selectedElement.text('Some text');            // insert text content
selectedElement.html('<div>some HTML</div>'); // insert HTML content

// creating new element and add class and id
const playersList = $('<ul>');
playersList.addClass('players').attr('id', 'my-players');
playersList.hasClass('players') === true;  // check class presence

// insert some elements into it
const playerItem = $('<li class="player">Ronaldo</li>');
playersList.append(playerItem); // append as the last element, same as element.appendTo(container);
playersList.prepend('<li class="player">Messi</li>'); // append as the first element
  • attributes, properties
const image = $('#image');

// get attributes of the selected element
const classValue = image.attr('class');
const sourceValue = image.attr('src');

// add an attribute to the selected element
image.attr('alt', 'This is my duckling');

// additional manipulations
image.removeAttr('alt');
image.removeClass('wp-img');
image.toggleClass('wp-img');
  • get and set values from inputs
const nameInput = $('#input-name');
const genderSelect = $('#select-gender');
const isStudentCheck = $('#check-student');

// set the value and get the value
nameInput.val('George');
const name = nameInput.val(); 
const gender = genderSelect.val();
isStudentCheck.prop('checked', true);
const isStudent = isStudentCheck.is(':checked'); 
nameInput.prop('disabled', true);
  • select multiple elements
const posts = $('.post'); // select by class name
posts.toggleClass('visited');
posts.hide();
posts.show();
const articles = $('.article');
// get only one element using its index
const articleAtIndex2 = articles.eq(2);
articleAtIndex2.siblings();// get all siblings
articleAtIndex2.next();    // get next "younger brother"
articleAtIndex2.nextAll(); // get all "younger brothers"
articleAtIndex2.prev();    // get next "older brother"
articleAtIndex2.prevAll(); // get all "older brothers"
articleAtIndex2.parent();  // get parent
articleAtIndex2.parent().parent(); // get grandparent

const playersContainer = $('#players');
playersContainer.children(); // get all immediate childrens 
playersContainer.children('.winner'); // get all immediate childrens matching the selector

// iterate through all children with the class .winner in a each loop
playersContainer.children('.winner').each(function () {
  const player = $(this);
});

// find all descendants matching the selector
playersContainer.find('.player-name');
  • selection filter methods
const articles = $('.article');

const newArticles = articles.filter('.new');
const articleAtIndex3 = articles.eq(3);
articleAtIndex3.is('.new') === true;

// and more filters
map(); not(); slice();
const articles = $('.article');
articles.eq(1).css('color');   // get a css property
articles.css('color', 'blue'); // set a css property
articles.css({ color: 'blue', background: 'red' });
articles.width();
articles.height();
articles.position();
articles.offset();
article.text('xyz'); 
article.html('<span id="score">42</span>');
article.empty();
article.remove();
article.replaceWith(anotherArticle);
article.after(articleAfter);
article.before(articleBefore);
article.append(articleDescription);
article.prepend(articleTitle);
element.animate();
element.fadeIn();
element.fadeOut();
element.hide();
element.show();
element.slideDown();
element.slideUp();
element.slideToggle();
element.toggle();
const button = $('#my-button');
button.click();                // trigger a click
button.click((e) => {}); // bind a click event
button.off('click');           // unbind a click event

$('#my-form').submit((e) => { e.preventDefault(); });
$('#my-input').focus((e) => { e.stopPropagation(); });
$('#my-checkbox').change((e) => { ... });
$('#my-textarea').blur((e) => { ... });

Best practices

  • CACHE YOUR SELECTORS IN VARIABLES
// Stores the live DOM element inside of a variable
const elem = $('#elem');

// Set's an element's title attribute using its current text
elem.attr('title', elem.text());

// Set's an element's text color to red
elem.css({ color: 'red' });

// Makes the element fade out
elem.fadeOut();

// Chaining
elem.attr('title', elem.text()).css({ color: 'red' }).fadeOut();
  • APPEND ONCE
// Dynamically building an unordered list from an array
const students = [{name: 'Greg', id: 1}, {name: 'Peter', id: 2}, {name: 'Kyle', id: 3}, {name: 'Danny', id: 4}, {name: 'Mark', id: 5}];
// select the container
const studentList = $("ul#student-list");
// create a temporary array for the elements
const studentElements = [];
// populate the temporary array with elements
students.forEach((student) => {
  const studentElement = $(`<li data-id="${student.id}">${student.name}</li>`);
  studentElement.click(() => {
    console.log(`You clicked ${student.id}, id: ${student.name}`);
  });
  studentElements.push(studentElement);
});
studentList.empty();
studentList.append(studentElements);
  • EVENT DELEGATION
const list = $('#list');
list.on('mouseenter', 'li', function () {
  $(this).text('Click me!');
});
list.on('click', 'li', function () {
  $(this).text('Why did you click this <li>?!');
});
  • AJAX wrappers nad promises
const createStudent = (studentData) => {
  return $.ajax({
    url: '/api/v1/student',
    type: 'POST',
    data: studentData,
  });
};
const studentForm = $('#student-form');
// create a new student in the API via a POST request and show the new student
studentForm.submit((e) => {
  e.preventDefault();
  // retrieve all form data, e.g.: { name: 'Dave' }
  const studentData = studentForm.serialize();
  createStudent(studentData).done((resp) => {
    // Updates the UI based the ajax result
    studentList.append(`<li>${resp.name}</li>`); 
  });
});
⚠️ **GitHub.com Fallback** ⚠️