0% found this document useful (0 votes)
11 views

3 - Javascript JQuery-MTD

Uploaded by

RIFQAH AMALIYAH
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

3 - Javascript JQuery-MTD

Uploaded by

RIFQAH AMALIYAH
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

CII3H4

Aplikasi Berbasis Platform

Javascript & jQuery


Objectives
 Student understands the usage of Javascript in the
web programming
 Student able to implement Javascript structure inside
HTML document
 Student able to integrate HTML + CSS+ Javascript on a
program
Javascript Overview
• Available on a browser at client side
• Used to make web pages interactive
• Insert dynamic text/tag into HTML (ex: comment box)
• React to events (ex: page load, user click, user input)
• Perform logic on user's computer (ex: form validation,
calculate total price in shopping cart)
• Javascript != Java
• NOT related to Java other than by name and some
syntactic similarities
Javascript Embed inside HTML

<!– some HTML code -->


<script type="text/javascript">
// Javascript code here
</script>
<!– some HTML code -->

• Embedded Javascript can be placed anywhere inside tag <body> in


HTML document
Linking to a external Javascript file
5

<script src="filename.js" type="text/javascript"></script>


HTML

• script tag usually placed in HTML page's <head> (like


linked CSS) or on the very bottom of HTML document
(before </html>)
• script code is stored in a separate file (xxx.js)
Variables and Data Types
• Rules of naming methods
• Case sensitive
• Start with a letter or underscore
• Must not a Javascript’s reserved word
• Must not contains operational characters

• Variable declaration:
• var variableName = value;
• variableName = value;
Variables
7

var name = expression; JS

var clientName = "Connie Client";


var age = 32;
var weight = 127.4; JS

• variables are declared with the var keyword (case sensitive) or


let
• doesn’t need to specify the type of variable, it’s automatically
adapt to the value within. But, JS has types ("loosely typed")
• Number, Boolean, String, Array, Object,
Function, Null, Undefined
• can find out a variable's type by calling typeof
Comments
8

// single-line comment
/* multi-line comment */
JS

• identical to Java's comment syntax


• recall: comment syntaxes
• HTML: <!-- comment -->
• CSS: /* comment */
Number type
9

var enrollment = 99;


var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3);
JS

• integer and real are the same type (Number)


• same operators like C or Java: + - * / % ++ -- = += -= *= /= %=
• similar precedence to Java
• many operators auto-convert types: "2" * 3 is 6
Boolean type
10

var iLike190M = true;


var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /* true */ }
if (0) { /* false */ }
JS
 any value can be used as a Boolean
 "falsey" values: 0, 0.0, NaN, "", null, and undefined
 "truthy" values: anything else from falsey values
 converting a value into a Boolean explicitly:
 var boolValue = Boolean(otherValue);
 var boolValue = !!(otherValue);
String type
11
var s = "Connie Client";
var name1 = s.substring(2, 8); // "nnie C"
var name2 = s.substr(2, 8); // "nnie Cli"
var len = s.length; // 13
var ie1 = s.indexOf('ie'); // 4
var ie2 = s.lastIndexOf('ie'); // 9
var firstName = s.substring(0, s.indexOf(" ")); //Conni
JS
• other methods: charAt, replace, split, join, reverse,
toLowerCase, toUpperCase
• charAt returns a one-letter String (there is no char type)
• length is a property (not a method as in Java)
• strings can be specified with double quote ("") or single quote ('')
• concatenation with + :
• 1 + 1 is 2, but "1" + 1 is "11"
More about String
12

 escape sequences behave as in Java:


\' \" \& \n \t \\
 converting between numbers and Strings:
var count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, full!"; // "10 bananas, full!"
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseFloat("booyah"); // NaN JS

• accessing the letters of a String:


var firstLetter = s[0]; // fails in IE
var firstLetter = s.charAt(0); // does work in IE
var lastLetter = s.charAt(s.length - 1);
JS
Splitting strings: split and join
13

var s = "the quick brown fox";


var a = s.split(" "); // ["the", "quick", "brown", "fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
JS

 split breaks apart a string into an array using a


delimiter
 can also be used with regular expressions (seen later)
 join merges an array into a single string, placing a
delimiter between them
Arrays
14

var name = []; // empty array


var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
JS

var ducks = ["Huey", "Dewey", "Louie"];


var len = ducks.length // 3
var stooges = []; // stooges.length is 0
stooges[0] = "Larry"; // stooges.length is 1
stooges[1] = "Moe"; // stooges.length is 2
stooges[4] = "Curly"; // stooges.length is 5
stooges[4] = "Shemp"; // stooges.length is 5
JS
Array methods
15
var a = ["Stef", "Jason"]; // Stef, Jason
a.push("Brian"); // Stef, Jason, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Brian
a.pop(); // Kelly, Stef, Jason
a.shift(); // Stef, Jason
a.sort(); // Jason, Stef
JS

 array serves as many data structures: list, queue,


stack, ...
 methods: concat, join, pop, push, reverse, shift,
slice, sort, splice, toString, unshift
 push and pop add / remove from back
 unshift and shift add / remove from front
 shift and pop return the element that is removed
Logical operators
16

 > < >= <= && || ! == != === !==


 most logical operators automatically convert types:
 5 < "7" is true
 42 == 42.0 is true
 "5.0" == 5 is true
 === and !== are strict equality tests; checks both
type and value
 "5.0" === 5 is false
if/else statement (same as Java)
17

if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
JS
 identical structure to Java's if/else statement
 Javascript allows almost anything as a condition
for loop
18
for (var i = 1; i < 7; i++) {
document.write("<h"+i+">Header "+i+"</h"+i+">");
}
// prints six HTML headers
JS

var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo" JS
while loops
19

while (condition) {
statements;
} JS

do {
statements;
} while (condition);
JS
Object
20

 Every element (HTML tag) in HTML document is a


Javascript object (DOM object)

 Object types
 Internal (built-in): String, Array, Math, Date
 External: All HTML elements in HTML document,
Window, user-defined object
DOM element objects
21
Math object
22

var rand1to10 = Math.floor(Math.random() * 10 + 1);


var three = Math.floor(Math.PI);
JS

 methods: abs, ceil, cos, floor, log,


max, min, pow, random, round, sin,
sqrt, tan
 properties: E, PI
Window object
23

 Document
 All HTML tags in HTML document is stored and can be
accessed with this object
 History
 Location
 Pop-up boxes (Alert, Confirm, Prompt)
Popup boxes
24
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS
Event-driven programming
25

 split breaks apart a string into an array using a


delimiter
 can also be used with regular expressions (seen later)
 join merges an array into a single string, placing a
delimiter between them
Javascript functions
26

function name() {
statement ;
statement ;
...
statement ;
} JS
//example
function mySalute() {
alert("Hello!");
alert("How are you?");
} JS

 function usually is stored in the contents of external JS file


linked to our HTML page
 statements placed into functions can be evaluated in
response to user events
Javascript functions
27

//function declaration
function add(bil1, bil2) {
var result= bil1 + bil2;
return result;
} JS

//function execution
mySalute(); //no return value
var val = add(3,7); //with return value, assign variable
document.write(add(3,7)); /* with return value, as input
for another function */
JS

 What will be printed on the screen?


Event handlers
28

<[element] ... on[event]="myFunction()"> ...


HTML

<button onclick="myFunction()">Click me!</button>


HTML
• Function in Javascript usually is used for event handler
• when we interact with a tag (element), function will be executed
• To able a tag to do the event handler, certain attribute must be added to
that tag, according to what event that tag want to capture. The attribute
for event handler starts with “on..”
• onclick is just one of attribute for event handler. Code example above
means: “if this button tag is clicked, then execute myFunction()”
• Another event handler attributes: onchange, onfocus, onblur,
onmouseover, onkeypress, etc
Document Object Model (DOM)
29

• JS can manipulates elements on


HTML document
• we can examine elements' state
• e.g. see whether a box is checked
• we can change state
• e.g. insert some new text into a div,
or add new div (box) into another
div
• we can change styles
• e.g. make a paragraph red
DOM element objects
30
Accessing object (HTML element)
31

 function document.getElementById(“x”) returns


the DOM object from the element which has the id
attribute value = “x”
 we can get or change the text in <input> element by
setting the value attribute
 we can get or change the text inside most elements by
setting the innerHTML attribute
Accessing object (HTML element)
32
 Example
// returns whole DOM object of element with id = “idname”
var obj = document.getElementById("idname");

// returns only the content of element with id = “idname”


// ex 1: get the content from element <input />
var val = document.getElementById("idname").value;
// ex 2: get the content from element other than <input />
var con = document.getElementById("idname").innerHTML;
JS
Manipulating element
33
<input id="textbox" type="text" />
<div id="output">replace me</div>
<button onclick="getValue()">Click me!</button>
<button onclick="changeText()">Click me too!</button>
HTML

function getValue() { //get the content of element


var text = document.getElementById("textbox").value;
var con = document.getElementById("output").innerHTML;
alert("value: " + text + " & " + con);
}
function changeText() { //manipulating element
//method 1: indirect, from returning object
var sp1 = document.getElementById("output");
sp1.innerHTML = "replaced! <br /> <button>New</button>";
//method 2: direct assignment on object attribute
document.getElementById("textbox").value = "Connie";
} JS
Any question?
jQuery
What is jQuery?
• jQuery is a lightweight, "write less, do more", JavaScript
framework.
• jQuery was originally released in January 2006 at BarCamp
NYC by John Resig and was influenced by Dean Edwards'
earlier cssQuery library
• The purpose of jQuery is to make it much easier to use
JavaScript on your website.
• jQuery takes a lot of common tasks that require many lines
of JavaScript code to accomplish, and wraps them into
methods that you can call with a single line of code.
• There are lots of other JavaScript frameworks out there,
but jQuery seems to be the most popular, and also the
most extendable.
Adding jQuery to Your Web Pages
• Download the jQuery library from jQuery.com
<head>
<script src="jquery-3.6.1.min.js"></script>
</head>
• or include jQuery from external URL (you must always
connect to internet)
<head>
<script src="https://code.jquery.com/jquery-
3.6.1.min.js"></script>
</head>
jQuery Syntax
• Basic syntax is: $(selector).action()
• A $ sign is to define/access jQuery
• A (selector) is to "query (or find)" HTML elements (like CSS
selector)
• An action() is a jQuery function to be performed on the
element(s)
• Examples:
• $("p").hide() - hides all <p> elements.
• $(".test").hide() - hides all elements with class="test".
• $("#test").hide() - hides the element with id="test".
The Document Ready Event
• You might have noticed that all jQuery methods are inside a document
ready event:
• This is to prevent any jQuery code from running before the document is
finished loading (is ready).
• It is good practice to wait for the document to be fully loaded and ready
before working with it. This also allows you to have your JavaScript code
before the body of your document, in the head section.

$(document).ready(function(){

// jQuery methods go here...

});

$(function(){

// jQuery methods go here...

});
jQuery Selectors
Syntax Description
$("*") Selects all elements

$(this) Selects the current HTML element

$("p.intro") Selects all <p> elements with class="intro"

$("p:first") Selects the first <p> element

$("ul li:first") Selects the first <li> element of the first <ul>

$("ul li:first-child") Selects the first <li> element of every <ul>

$("[href]") Selects all elements with an href attribute

$("a[target='_blank']") Selects all <a> elements with a target attribute value equal to "_blank"

$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT equal to "_blank"

$(":button") Selects all <button> elements and <input> elements of type="button"

$("tr:even") Selects all even <tr> elements

$("tr:odd") Selects all odd <tr> elements


jQuery Event Methods
• click, keypress, submit, load, dblclick, keydown,
change, resize, mouseenter, keyup, focus, scroll,
mouseleave, blur, unload

$(document).ready(function(){
$("p").click(function(){
// action goes here!!
});
});
jQuery - Get Content and Attributes
• Three simple, but useful, jQuery methods for DOM manipulation are:
• text() - Sets or returns the text content of selected elements
• html() - Sets or returns the content of selected elements (including HTML
markup)
• val() - Sets or returns the value of form fields
• $("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
• The jQuery attr() method is used to get attribute values.
• $("button").click(function(){
alert($("#w3s").attr("href"));
});
• The jQuery data() method is used to get attribute values.
• $("button").click(function(){
alert($("#w3s").data(“option"));
});
jQuery - Set Content and Attributes
• We will use the same three methods from the previous page
to set content:
• text() - Sets or returns the text content of selected elements
• html() - Sets or returns the content of selected elements (including
HTML markup)
• val() - Sets or returns the value of form fields
• $("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
• The jQuery attr() method is also used to set/change attribute
values.
• $("button").click(function(){
$("#w3s").attr({
"href" : "https://www.w3schools.com/jquery/",
"title" : "W3Schools jQuery Tutorial"
});
});
jQuery - Add Elements
• We will look at four jQuery methods that are used to add new content:
• append() - Inserts content at the end of the selected elements
• $("table").append("<tr><td>add row append table</td></tr>");
• prepend() - Inserts content at the beginning of the selected elements
• $("table").append("<tr><td>add row prepend table</td></tr>");
• after() - Inserts content after the selected elements
• $("p").after("<span>Some text after</span>");
• before() - Inserts content before the selected elements
• $("p").after("<span>Some text before</span>");
jQuery - Remove Elements
• remove() - Removes the selected element (and its
child elements)
• $("#div1").remove();
• empty() - Removes the child elements from the
selected element
• $("#div1").empty();
• The following example removes all <p> elements with
class="test" and class="demo":
• $("p").remove(".test, .demo");
jQuery - Get and Set CSS Classes
• Query has several methods for CSS manipulation. We will
look at the following methods:
• addClass() - Adds one or more classes to the selected
elements
• $("h1, h2, p").addClass("blue");
• removeClass() - Removes one or more classes from the
selected elements
• $("h1, h2, p").removeClass("blue");
• toggleClass() - Toggles between adding/removing classes
from the selected elements
• $("h1, h2, p").toggleClass("blue");
• css() - Sets or returns the style attribute
• $("p").css("background-color", "yellow");
jQuery Dimension Methods
• jQuery has several important methods for working
with dimensions:
• width()
• height()
• innerWidth()
• innerHeight()
• outerWidth()
• outerHeight()

• $("button").click(function(){
var txt = "";
txt += "Width: " + $("#div1").width();
txt += "Height: " + $("#div1").height();
$("#div1").html(txt);
});
Looping over the DOM
<ul>
<li>foo</li>
<li>bar</li>
</ul>

$( "li" ).each(function() {
$( this ).addClass( "foo" );
});
Any question?
Exercise
• Create a function that calculates only the odd values in
a sequence of numbers, given the min and max
sequence value as inputs. Example:
• min = 1, max = 8, result = 16 (1+3+5+7)
• min = 4, max = 15, result = 60 (5+7+9+11+13+15)
• Open your previous CSS exercise file, add two buttons
that call a function when clicked:
• First button: change the alignment of the text to center or
right
• Second button: change the background color of one of the
box. When button is clicked again, the background color is
back to original color
References
• https://www.w3schools.com/js/default.asp
• http
://www.webstepbook.com/supplements-2ed/slides/le
ctureXX-jquery.shtml
• https://api.jquery.com
• https://www.w3schools.com/jquery/
THANK YOU

You might also like