JavaScript technologies

jQuery

Horváth, Győző
senior lecturer
horvath.gyozo@inf.elte.hu

Financed from the financial support ELTE won from the Higher Education Restructuring Fund of the Hungarian Government

jQuery

DOM abstraction

Basic conceptions

  • DOM abstractions (browser-independence)
  • Convenient API
  • Further services

Main concept

  • Selecting elements
  • Operations on the selected elements
$('p').hide();

Selecting elements

  • CSS 1,2,3 selectors
    • additional jQuery selectors
$("#profilkep");
$(".adat");
$("li");
$("div.adat");
$("#profilkep, #adatok");
$("img[src=profil.jpg]");
$("ul li.adat b");
$("ul li:first");
$("b:contains('Végzettség:')");

Operations

  • DOM traversal (selecting elements with relative paths)
  • Manipulating attributes
  • Manipulating elements
    • creating
    • modifying
    • deleting
  • Event handling
  • Style manipulations
  • AJAX abstraction (later in this course)
  • Other helper functions

DOM traversal

  • children (children()), descendants (find())
  • parent(s) (parent(), parents(), parentsUntil()), closest ancestor (closest())
  • siblings (siblings(), next(), nextAll(), nextUntil(), prev(), prevAll(), prevUntil())
// selecting the parent element
$("#adatok").parent();    
// selecting the next element
$("li").next();              
// selecting the previous element
$("li").prev();              
// selecting the previous element, but only if its classname is 'data
$("li").prev(".data");       
// the first ancestor of the element which is div
$("b:first").closest('div'); 
// the descendants of the element which are of class 'data'
$("#adatok").find(".data");  
// the first of the selected items
$("li").first();           
// the last of the selected items
$("li").last();              
// the third of the selected items
$("li").eq(2);               
// the siblings of the element which are h1
$("#adatok").siblings("h1");

Changing the scope of the selected items

  • filtering (is(), has(), filter(), first(), last())
  • adding (add())
// Filtering
// adding all the li elements to the jQuery object of the already selected element
$("#dataDiv").add("li");      
// removing all the li elements from the selected elements
$("#dataDiv, li").not("li");  
// only the images remain among the selected elements
$(".data").filter("img");    

//Back-step selection
$("#dataDiv")                                        // scope: div#dataDiv
    .find("li")                                      // scope: div#dataDiv
        .css({ padding: "5px" })                     // scope: div#dataDiv li
        .find("b")                                   // scope: div#dataDiv li
            .html('Modifying texts!!!')              // scope: div#dataDiv li b
            .end()                                   // scope: div#dataDiv li b
        .end()                                       // scope: div#dataDiv li
    .animate({ paddingTop: '+=100' }, 200); 

Iterating the selected items

var labels = [];
$("b").each(function() {
    labels.push( $(this).text().replace(':','') );
});
labels.join(', ');

Changing the HTML structure

  • creating element(s) (jQuery(HTMLString))
  • copying elements (clone())
  • adding and moving element (append(), prepend(), after(), before(), appendTo(), prependTo(), insertAfter(), insertBefore(), replace())
  • deleting element (remove(), detach())
  • content management (html(), text())
  • attribute management (attr())

Changing the HTML structure

// Creating new jQuery objects
var $a = $("<a class='12a' href='index.html'><b>Hello</b></div>");

// Similar element definition
var $a = $("<a />", {
               className: '12a',
               href: 'index.html',
               html: '<b>Hello</b>'
           });

// Changing content and attribute value
$("<a />")
    .addClass('12a')
    .attr('href', 'index.html')
    .html('<b>Hello</b>')
    .appendTo($("body"));

$("body").find('.12a').attr('href'); // => 'index.html'
$("body").find('.12a').html();       // => '<b>Hello</b>', HTML content
$("body").find('.12a').text();       // => 'Hello', content without tags

//inserting and deleting jQuery objects
$a.appendTo($("body"));        // inserting $a to the end of the body
$a.prependTo($("body"));       // inserting $a to the top of the body
$a.insertAfter($("#dataDiv")); // inserting $a after dataDiv
$a.insertBefore($("#dataDiv"));// inserting $a before dataDiv
$a.remove();                   // deleting $a

//The same from another point of view
$("body").append($a);          
$("body").prepend($a);         
$("#adatok").after($a);        
$("#adatok").before($a);       

Style management

  • css()
  • addClass(), removeClass(), toggleClass(), hasClass()
  • animate()
  • show(), hide(), toggle()
  • fadeIn(), fadeOut(), fadeToggle()
  • slideDown(), slideUp(), slideToggle()
  • height(): computed height
  • innerHeight(): height + padding
  • outerHeight(): height + padding + border (+margin with true parameter)
  • width(), innerWidth(), outerWidth(): see height
  • position(): location relative to the parent object (top, left)
  • offset(): location relative to the document (top, left)
  • scrollTop(), scrollLeft()

Event handling

  • $obj.on('type', fn): direct assignment
  • $obj.on('type', 'selector', fn): event delegation
$('table').on('click', 'td', function (e) {
    console.log(this);
    console.log(e);
});

//Namespacing
$('table').on('click.myGame', 'td', function () {});
$('table').off('click.myGame', 'td', function () {});

//Even better
$('table').off('click.myGame').on('click.myGame', 'td', function () {});

Task

Rewrite the previous application using jQuery!

jQuery CDN

https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js

UI elements

class ListView {
    constructor(props) {
        props = props || {};
        this.list = props.snippets;
        $('#text-filter').on('keyup', this.onKeyUp.bind(this));
    }
    makeListItemsFromArray(arr) {
        /* ... */
    }
    onKeyUp(e) {
        var filterText = e.currentTarget.value;
        var filteredTitles = this.list.getTitles(filterText);
        $('#code-list').html( this.makeListItemsFromArray(filteredTitles) );
    };
}