Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Quick intro to JQuery

Quick intro to JQuery

Jussi Pohjolainen

September 25, 2019
Tweet

More Decks by Jussi Pohjolainen

Other Decks in Technology

Transcript

  1. 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
  2. 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+
  3. 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
  4. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>HTML5 Page</title>

    <!-- <script src="node_modules/jquery/dist/jquery.min.js"></script> --> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous" ></script> </head> <body></body> </html> Using CDN Using Downloaded jquery file via npm
  5. 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”
  6. 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
  7. 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’))
  8. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>HTML5 Page</title>

    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous" ></script> </head> <body> <button>Click</button> <script> jQuery(() => { jQuery('button').click(() => alert('clicked')) }); </script> </body> </html> When DOM is ready to be manipulated, add a click event to the button.
  9. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>HTML5 Page</title>

    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous" ></script> </head> <body> <button>Click</button> <script> $(() => { $('button').click(() => alert('clicked')) }); </script> </body> </html> The same but replacing jQuery with $
  10. Example of Setting a Class <!DOCTYPE html> <html lang="en"> …

    <style> .background-red { background-color: RGB(255, 0, 0); } </style> </head> <body> <button>Click</button> <script> $(() => { $("button").click(() => $("button").addClass("background-red")); }); </script> </body> </html> Class CSS Adding a class dynamically for the button
  11. Example of Removing a Class <script> $(() => { $("button").click(()

    => { if ($("button").hasClass("background-red")) { $("button").removeClass("background-red"); } else { $("button").addClass("background-red"); } }); }); </script> If button has a class, then remove the class
  12. Also toggle <script> $(() => { $("button").click(() => { $("button").toggle("background-red")

    }); }); </script> If button has a class, then remove the class
  13. Conflict? <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous" ></script> <script> let $ =

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

    $newVariable = jQuery.noConflict(); $newVariable(() => { $newVariable("button").click(event => { alert("hello"); }); }); </script> Possible to create another variable that replaces the original $ in JQuery
  15. Solution 2 todo <script> jQuery(($) => { $("button").click(event => {

    alert("hello"); }); }); </script> You can use the $ inside of a function by adding argument
  16. 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" );
  17. Refining & Filtering Selections (JQuery Doc) • div.foo elements that

    contain <p> tags • $( "div.foo" ).has( "p" ); • <h1> 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 );
  18. Attributes <script> $(() => { $("a").attr({title: "to apple's website", href:

    "http://www.apple.com"}); $("a").html("Apple") }); </script> </head> <body> <a href="http://www.microsoft.com">Microsoft</a> </body> You can change attributes using attr - function
  19. Working with Elements <script> $(() => { $("a").html("Microsoft") let text

    = $("a").html() $("h1").html(text) }); </script> </head> <body> <h1>Welcome</h1> <a href="http://www.apple.com">Apple</a> </body> Setter Getter H1 will have ”Microsoft”
  20. Working with Elements <script> $(() => { $("a").html("Microsoft") }); </script>

    </head> <body> <h1>Welcome</h1> <a href="http://www.apple.com">Apple</a> <a href="http://www.apple.com">Apple</a> </body> Changes both
  21. Mixing with DOM <script> $(() => { let a =

    document.querySelector("a") $(a).html("Microsoft") }); </script> </head> <body> <h1>Welcome</h1> <a href="http://www.apple.com">Apple</a> <a href="http://www.apple.com">Apple</a> </body> a is a DOM element Only the first one changes
  22. Working with Elements <script> $(() => { let h3array =

    $("section").find("h3") h3array[2].innerHTML = 'kk’ h3array.eq(2).html('hello world') }); </script> </head> <body> <section> <h3>Hello 1</h3> <h3>Hello 2</h3> <h3>Hello 3</h3> </section> </body> 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
  23. Working with Elements <script> $(() => { $("section") .find("h3") .eq(2)

    .html("hello world") .end() .eq(0) .html("hello world") }); </script> </head> <body> <section> <h3>Hello 1</h3> <h3>Hello 2</h3> <h3>Hello 3</h3> </section> </body> Restores the JQuery object
  24. 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.
  25. Moving Elements • .insertAfter() • .after() • .insertBefore() • .before()

    • .appendTo() • .append() • .prependTo() • .prepend
  26. Example <script> $(() => { // Fetch all li's $("li")

    .eq(0) // reduce the array to one .appendTo("ul"); // move this li to the last }); </script> <ul> <li>A</li> <li>B</li> <li>C</li> </ul>
  27. Using CSS selectors <script> $(() => { // Fetch all

    li's $("ul li:first") .appendTo("ul"); // move this li to the last }); </script> <ul> <li>A</li> <li>B</li> <li>C</li> </ul>
  28. append vs appendTo <script> $(() => { let li =

    $( "ul li:first" ) $("ul").append(li); }); </script> <ul> <li>A</li> <li>B</li> <li>C</li> </ul> <script> $(() => { let li = $( "ul li:first" ) li.appendTo("ul"); }); </script> <ul> <li>A</li> <li>B</li> <li>C</li> </ul>
  29. Clone <script> $(() => { let li = $( "ul

    li:first" ) $("ul").append(li.clone()) }); </script> <ul> <li>A</li> <li>B</li> <li>C</li> </ul> Clones the <li>A</li> to the ul -list
  30. Creating new elements • If a string is passed to

    $() that looks like an html, jquery creates a new element • let newP = $("<p>new element</p>") • And if you want to reference existing element, then • let existingP = $("p")
  31. Creating New Elements <script> $(() => { let li =

    $("<li>D</li>") $("ul").append(li) }); </script> <ul> <li>A</li> <li>B</li> <li>C</li> </ul>
  32. Iterating <script> $(() => { $("li").each(function(index, element) { $(element).html("hello") });

    }); </script> <ul> <li>A</li> <li>B</li> <li>C</li> </ul> Normal DOM element
  33. Traversing: parents … <script> $(() => { // <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") ); }); </script> <div> <ul> <li>A</li> <li>B</li> </ul> </div> </body>
  34. Traversing: children <script> $(() => { // <ul>, <li> ..

    console.log( $("div").children() ); // <li>, <li> console.log( $("div").find("li") ); }); </script> <div> <ul> <li>A</li> <li>B</li> </ul> </div>
  35. Traversing: siblings <body> <script> $(() => { // <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() ); }); </script> <div> <ul> <li>A</li> <li>B</li> <li>C</li> </ul> </div> </body>
  36. 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' })
  37. CSS: classes • Add • $('h1').addClass('headingcolor') • Remove • $('h1').removeClass('headingcolor')

    • Toggle • $('h1').toggleClass('headingcolor') • Toggle • if ( $('h1').hasClass('headingcolor') ) { .. }
  38. 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()
  39. 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
  40. Event object <script> $(() => { $("#name").keyup((event) => { let

    text = event.target.value $("h1").html(text) }) }); </script> <h1>Name</h1> <input id="name" type="text" placeholder="give name" name="name" /> The event object gives you information about the event Fetching the event target’s value
  41. 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
  42. Simple AJAX DELETE let conf = { url: 'http://localhost:8080/customer/1', type:

    "DELETE" } $.ajax(conf) .done(result => alert("deleted")) .fail(() => alert(error))
  43. Show and hide elements • Hide all paragraphs • $(

    "p" ).hide() • Show all paragraps • $( "p" ).show() • This will change CSS and sets display to none
  44. Example <script> $(() => { $("button:first").click(() => $("h1").show()); $("button:last").click(() =>

    $("h1").hide()); }); </script> <button>Show</button><button>Hide</button> <h1>Title</h1>
  45. 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)
  46. 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")
  47. Using animations: toggle • You can also toggle the visibility

    • Examples • $( "p" ).toggle() • $( "p" ).slideToggle("fast") • $( "p" ).fadeToggle(800)
  48. 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'))