P Tutorial jQuery - nvbach91/4IZ268-2024-2025-ZS GitHub Wiki

  • motivation

image

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.slim.min.js" defer></script>
const init = () => {
  // initialize app
  // start scripting
  const someLocalVariable = 0;
  // do stuff with the DOM
  // call some ajax requests...
};
$(document).ready(init);
  • differences compared to modern JS
const articleHeadingText = 'Article Heading';
const articleParagraphText = 'Article text lorem ipsum';
const imageSrc = 'https://some.image.com/image.jpg';
const imageAlt = 'Some image';

// modern JS - creating elements in a structure
const articleElement = document.createElement('article');
const articleHeading = document.createElement('h3');
articleHeading.textContent = articleHeadingText;
const articleParagraph = document.createElement('p');
articleParagraph.textContent = articleParagraphText;
const imageElement = document.createElement('img');
imageElement.src = imageSrc;
imageElement.alt = imageAlt;
imageContainer.append(imageElement);

// jQuery - creating elements in a structure
const article = $(`
    <article>
        <h3>${articleHeadingText}</h3>
        <p>${articleParagraphText}</p>
        <img src="${imageSrc}" alt="${alt}">
    </article>
`);

// modern JS - selecting element and adding event listener
const button = document.querySelector('#my-button');
button.addEventListener('click', () => {
    console.log('Clicked');
});

// jQuery - selecting element and adding event listener
$('#my-button').click(() => {
    console.log('Clicked');
});
  • 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.on('click', (e) => {}); // bind a click event
button.off('click');           // unbind a click event

$('#my-form').on('submit', (e) => { e.preventDefault(); });
$('#my-input').on('focus', (e) => { e.stopPropagation(); });
$('#my-checkbox').on('change', (e) => { ... });
$('#my-textarea').on('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.on('click', () => {
    console.log(`You clicked ${student.id}, id: ${student.name}`);
  });
  studentElements.push(studentElement);
});
studentList.empty();
studentList.append(studentElements);
  • EVENT DELEGATION - delegace eventu na vnitřní elementy
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>?!');
});
⚠️ **GitHub.com Fallback** ⚠️