Slide 1

Slide 1 text

Quick Intro To JQuery Jussi Pohjolainen

Slide 2

Slide 2 text

Why? • Wikipedia; • "Web analysis indicates that it is the most widely deployed JavaScript library by a large margin" • Easier way of manipulating DOM • Elimination of cross-browser incompatibilities

Slide 3

Slide 3 text

Browser Support • Desktop • Chrome: (Current - 1) and Current • Edge: (Current - 1) and Current • Firefox: (Current - 1) and Current, ESR • Internet Explorer: 9+ • Safari: (Current - 1) and Current • Opera: Current • Mobile • Stock browser on Android 4.0+ • Safari on iOS 7+

Slide 4

Slide 4 text

Download • You can just download from the web site • https://jquery.com/download/ • Or you can • npm install jquery • Or you can use CDN • https://code.jquery.com

Slide 5

Slide 5 text

HTML5 Page Using CDN Using Downloaded jquery file via npm

Slide 6

Slide 6 text

Vanilla JS: When Page is Loaded window.onload = () => console.log(’page is loaded’) ”The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading”

Slide 7

Slide 7 text

JQuery: When Page is ready to be manipulated jQuery(document).ready(() => console.log(’page is ready’) ”The .ready() method offers a way to run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate.” => Your code can be run before downloading large images

Slide 8

Slide 8 text

JQuery 3.0: Preferred Way jQuery(() => console.log(’page is ready’))

Slide 9

Slide 9 text

jQuery() or $() function • The jQuery() function can be also written as $() • Can be used to search for DOM elements in the HTML page • Example • $(’button’).click(() => console.log(’clicked’))

Slide 10

Slide 10 text

HTML5 Page Click jQuery(() => { jQuery('button').click(() => alert('clicked')) }); When DOM is ready to be manipulated, add a click event to the button.

Slide 11

Slide 11 text

HTML5 Page Click $(() => { $('button').click(() => alert('clicked')) }); The same but replacing jQuery with $

Slide 12

Slide 12 text

Example of Setting a Class … .background-red { background-color: RGB(255, 0, 0); } Click $(() => { $("button").click(() => $("button").addClass("background-red")); });

Slide 13

Slide 13 text

Example of Removing a Class $(() => { $("button").click(() => { if ($("button").hasClass("background-red")) { $("button").removeClass("background-red"); } else { $("button").addClass("background-red"); } }); }); If button has a class, then remove the class

Slide 14

Slide 14 text

Also toggle $(() => { $("button").click(() => { $("button").toggle("background-red") }); }); If button has a class, then remove the class

Slide 15

Slide 15 text

Exercise

Slide 16

Slide 16 text

JQuery Core

Slide 17

Slide 17 text

Conflict? let $ = "hello"; $(() => { $("button").click(event => { alert("hello"); }); }); If some other script uses the $ variable, we have a conflict Will fail because we are not using $ function from the JQuery library

Slide 18

Slide 18 text

Solution 1 let $ = "hello"; var $newVariable = jQuery.noConflict(); $newVariable(() => { $newVariable("button").click(event => { alert("hello"); }); }); Possible to create another variable that replaces the original $ in JQuery

Slide 19

Slide 19 text

Solution 2 todo jQuery(($) => { $("button").click(event => { alert("hello"); }); }); You can use the $ inside of a function by adding argument

Slide 20

Slide 20 text

Selecting Elements (JQuery Doc) • Selecting Elements by ID • $( "#myId" ); • Selecting Elements by Class Name • $( ".myClass" ); • Selecting Elements by Attribute • $( "input[name='first_name']" ); • Selecting Elements by Compound CSS Selector • $( "#contents ul.people li" ); • Selecting Elements with a Comma-separated List of Selectors • $( "div.myClass, ul.people" );

Slide 21

Slide 21 text

Refining & Filtering Selections (JQuery Doc) • div.foo elements that contain

tags • $( "div.foo" ).has( "p" ); •

elements that don't have a class of bar • $( "h1" ).not( ".bar" ); • unordered list items with class of current • $( "ul li" ).filter( ".current" ); • just the first unordered list item • $( "ul li" ).first(); • the sixth • $( "ul li" ).eq( 5 );

Slide 22

Slide 22 text

Attributes $(() => { $("a").attr({title: "to apple's website", href: "http://www.apple.com"}); $("a").html("Apple") }); Microsoft You can change attributes using attr - function

Slide 23

Slide 23 text

Working with Elements $(() => { $("a").html("Microsoft") let text = $("a").html() $("h1").html(text) });

Welcome

Apple Setter Getter H1 will have ”Microsoft”

Slide 24

Slide 24 text

Working with Elements $(() => { $("a").html("Microsoft") });

Welcome

Apple Apple Changes both

Slide 25

Slide 25 text

Mixing with DOM $(() => { let a = document.querySelector("a") $(a).html("Microsoft") });

Welcome

Apple Apple a is a DOM element Only the first one changes

Slide 26

Slide 26 text

Working with Elements $(() => { let h3array = $("section").find("h3") h3array[2].innerHTML = 'kk’ h3array.eq(2).html('hello world') });

Hello 1

Hello 2

Hello 3

jQuery object contains a collection of Document Object Model (DOM) elements. It is array like object, but not array Demonstration of DOM Eq – function creates new jQuery object from one element with the list

Slide 27

Slide 27 text

Working with Elements $(() => { $("section") .find("h3") .eq(2) .html("hello world") .end() .eq(0) .html("hello world") });

Hello 1

Hello 2

Hello 3

Restores the JQuery object

Slide 28

Slide 28 text

Manipulating Elements (JQuery Doc) • .html() • Get or set the HTML contents. • .text() • Get or set the text contents; HTML will be stripped. • .attr() • Get or set the value of the provided attribute. • .width() • Get or set the width in pixels of the first element in the selection as an integer. • .height() • Get or set the height in pixels of the first element in the selection as an integer. • .position() • Get an object with position information for the first element in the selection, relative to its first positioned ancestor. This is a getter only. • .val() • Get or set the value of form elements.

Slide 29

Slide 29 text

Moving Elements • .insertAfter() • .after() • .insertBefore() • .before() • .appendTo() • .append() • .prependTo() • .prepend

Slide 30

Slide 30 text

Example $(() => { // Fetch all li's $("li") .eq(0) // reduce the array to one .appendTo("ul"); // move this li to the last });
  • A
  • B
  • C

Slide 31

Slide 31 text

Using CSS selectors $(() => { // Fetch all li's $("ul li:first") .appendTo("ul"); // move this li to the last });
  • A
  • B
  • C

Slide 32

Slide 32 text

append vs appendTo $(() => { let li = $( "ul li:first" ) $("ul").append(li); });
  • A
  • B
  • C
$(() => { let li = $( "ul li:first" ) li.appendTo("ul"); });
  • A
  • B
  • C

Slide 33

Slide 33 text

Clone $(() => { let li = $( "ul li:first" ) $("ul").append(li.clone()) });
  • A
  • B
  • C
Clones the
  • A
  • to the ul -list

    Slide 34

    Slide 34 text

    Creating new elements • If a string is passed to $() that looks like an html, jquery creates a new element • let newP = $("

    new element

    ") • And if you want to reference existing element, then • let existingP = $("p")

    Slide 35

    Slide 35 text

    Creating New Elements $(() => { let li = $("<li>D</li>") $("ul").append(li) });
    • A
    • B
    • C

    Slide 36

    Slide 36 text

    Remove $(() => { $("ul li:first").remove() });
    • A
    • B
    • C

    Slide 37

    Slide 37 text

    Iterating $(() => { $("li").each(function(index, element) { $(element).html("hello") }); });
    • A
    • B
    • C
    Normal DOM element

    Slide 38

    Slide 38 text

    Exercise

    Slide 39

    Slide 39 text

    Traversing: parents … $(() => { // <ul> console.log( $("li").parent() ); // <ul>, <div>, <body>, <html> console.log( $("li").parents() ); // <div> console.log( $("li").parents("div") ); // <ul>, <div> console.log( $("li").parentsUntil("body") ); });
    • A
    • B

    Slide 40

    Slide 40 text

    Traversing: children $(() => { // <ul>, <li> .. console.log( $("div").children() ); // <li>, <li> console.log( $("div").find("li") ); });
    • A
    • B

    Slide 41

    Slide 41 text

    Traversing: siblings $(() => { // <li>B</li>, <li>C</li> console.log( $("ul li:first").siblings() ); // <li>B</li> console.log( $("ul li:first").next() ); // <li>B</li> console.log( $("ul li:last").prev() ); });
    • A
    • B
    • C

    Slide 42

    Slide 42 text

    CSS • Getting CSS • const color = $('h1').css('color') • Setting CSS • $('h1').css('color', 'blue') • Setting multiple values by giving an object • $('h1').css({ color: 'blue', 'font-size': '100px' })

    Slide 43

    Slide 43 text

    CSS: classes • Add • $('h1').addClass('headingcolor') • Remove • $('h1').removeClass('headingcolor') • Toggle • $('h1').toggleClass('headingcolor') • Toggle • if ( $('h1').hasClass('headingcolor') ) { .. }

    Slide 44

    Slide 44 text

    Utility • $.trim() • const x = $.trim(' lots of extra whitespace ') • $.each() • $.each(['jack', 'tina', 'paul'], (key, value) => console.log(`${key} = ${value}`)) • $.each({ name: 'jack', age: 40 }, (key, value) => console.log(`${key} = ${value}`)) • $.inArray() • console.log($.inArray(4, [1, 2, 3, 4])) // outputs 3 • $.extend()

    Slide 45

    Slide 45 text

    Events

    Slide 46

    Slide 46 text

    on() $( "p" ).on( "click", function() { console.log( "click" ); }); $( "p" ).click(function() { console.log( "You clicked a paragraph!" ); }); Then on function can be used for different events Shortcut functions available for most common events

    Slide 47

    Slide 47 text

    Event object $(() => { $("#name").keyup((event) => { let text = event.target.value $("h1").html(text) }) });

    Name

    The event object gives you information about the event Fetching the event target’s value

    Slide 48

    Slide 48 text

    Exercise

    Slide 49

    Slide 49 text

    Connecting to Backend

    Slide 50

    Slide 50 text

    Simple HTTP GET $.ajax('https://swapi.co/api/people/’) .done((result) => console.log(result)) .fail(() => alert('fail'))

    Slide 51

    Slide 51 text

    Simple HTTP POST let conf = { url: "http://.....", data: JSON.stringify({lat: 44, lon: 44}), type: "POST", contentType: "application/json" } $.ajax(conf).done((result) => alert("success")) Sending JSON

    Slide 52

    Slide 52 text

    Simple AJAX DELETE let conf = { url: 'http://localhost:8080/customer/1', type: "DELETE" } $.ajax(conf) .done(result => alert("deleted")) .fail(() => alert(error))

    Slide 53

    Slide 53 text

    Exercise

    Slide 54

    Slide 54 text

    Effects

    Slide 55

    Slide 55 text

    Show and hide elements • Hide all paragraphs • $( "p" ).hide() • Show all paragraps • $( "p" ).show() • This will change CSS and sets display to none

    Slide 56

    Slide 56 text

    Example $(() => { $("button:first").click(() => $("h1").show()); $("button:last").click(() => $("h1").hide()); }); ShowHide

    Title

    Slide 57

    Slide 57 text

    Using animations • Hide all paragraphs with fast animation • $( "p" ).hide("fast") • $( "p" ).hide(500) • Show all paragraps with slow animation • $( "p" ).show("slow") • $( "p" ).show(1500)

    Slide 58

    Slide 58 text

    Using animations: slide and fade • Hide and show will use two effects by default • slide • fade • If you prefer only one effect you can • $( "p" ).slideUp("fast") • $( "p" ).slideDown("fast") • $( "p" ).fadeIn("fast") • $( "p" ).fadeOut("fast")

    Slide 59

    Slide 59 text

    Using animations: toggle • You can also toggle the visibility • Examples • $( "p" ).toggle() • $( "p" ).slideToggle("fast") • $( "p" ).fadeToggle(800)

    Slide 60

    Slide 60 text

    Triggering function after animation completes • Use callback function to trigger action when animation completes • Example • $( "p" ).fadeToggle(800, () => alert('done’)) • Keyword this refers to the element that did the animation • $( "p" ).fadeToggle(800, () => $(this).addClass('change'))

    Slide 61

    Slide 61 text

    Exercise