Teori 7 – Pemograman Web (IS 204)
Teori 9 -
What is jQuery?
Sebuah framework untuk JavaScript
Memudahkan pemrograman JavaScript
Reduce code
Separate behaviour from structure
Open Source Project dibuat oleh John Resig
di Rochester Institute of Technology
“Why should web developers be forced to write long, complex, book-length
pieces of code when they want to create simple pieces of interaction”
What is available for JQuery
Cross browser support and detection
AJAX functions
CSS functions
DOM manipulation
DOM transversal
Attribute manipulation
Event detection and handling
JavaScript animation
Hundreds of plugins for pre-built user interfaces,
advanced animations, form validation, etc
Expandable functionality using custom plugins
Document Object Model (DOM)
jQuery adalah “DOM scripting”
DOM adalah struktur hirarki dari halaman web
DOM ini bisa ngapain sih?
Menambah dan mengurangi element DOM secara
“on the fly”
Mengubah properti dan nilai dari element DOM
secara “on the fly”
Mengakses dan mengganti style dari DOM secara
“on the fly”
HTML DOM Tree Example
HTML DOM Properties
x.innerHTML - the text value of x
x.nodeName - the name of x
x.nodeValue - the value of x
x.parentNode - the parent node of x
x.childNodes - the child nodes of x
x.attributes - the attributes nodes of x
HTML DOM Method
x.getElementById(id) - get the element with a
specified id
x.getElementsByTagName(name) - get all
elements with a specified tag name
x.appendChild(node) - insert a child node to x
x.removeChild(node) - remove a child node
from x
Example DOM
<html>
<head>
<script type="text/javascript">
window.onload = function (){
nodeValue=document.getElementById("intro").childNodes[0].nodeValue;
nodeName=document.getElementById("intro").nodeName;
innerHTML=document.getElementById("intro").innerHTML;
attributes=document.getElementById("intro").attributes;
parentNode=document.getElementById("intro").parentNode;
document.write(
"Node Value = "+nodeValue+ HASIL :
"<br/>Node Name = "+nodeName+
"<br/>innerHTML = "+innerHTML+
"<br/>attributes = "+attributes+
"<br/>parentNode = "+parentNode);
}
</script>
</head>
<body>
<p id="intro">Hello World!</p>
</body>
</html>
Kenapa tidak pakai DOM ?
Karena...
DOM tree terlalu kaku untuk digunakan
Tidak ada multiple handlers per event
Browser incompatibilities
Tidak ada high-level function
Perbedaan Jumlah Kode DOM dengan
JQuery
Dengan DOM
var fieldsets = document.getElementsByTagName('fieldset');
var legend, fieldset;
for (var i = 0; fieldset = fieldsets[i]; i++) {
if (!hasClass(fieldset, 'collapsible')) {
continue;
}
legend = fieldset.getElementsByTagName('legend');
if (legend.length == 0) {
continue;
}
legend = legend[0];
...
}
Dengan JQuery
$('fieldset.collapsible legend').each(function () {...});
JQuery: Fundamental
Template Jquery :
<html>
<head>
<script type=“text/javascript” src=“jquery.js”/>
<script type=“text/javascript”>
//taruh kode jquery / javascript disini
</script>
</head>
<body>
</body>
</html>
Kode warna merah adalah kode untuk import framework jquery
Document Ready Handler
Jalankan kode jika dokument sudah diload
semua.
jQuery memiliki fungsi sederhana untuk
mengecek apakah dokument sudah berhasil
diload semua yaitu ready event.
$(document).ready(function(){
//kode anda
});
jQuery Wrapper (1)
jQuery menyediakan sebuah kelas yang
bertindak sebagai wrapper untuk object lain.
Konsep wrapper mirip dengan adapter pada
OOP
Dalam jQuery hampir semua operasi
menggunakan jQuery wrapper
Kelas jQuery dipetakan dengan tanda $
jQuery object dapat melakukan proses wrap
pada object yang berbeda-beda
jQuery Wrapper (2)
Contoh :
Wrap element html
$(“<p>What's cooking?</p>”)
Anda dapat menggunakan appendTo jika ingin
meletakkan kalimat What's cooking?
tersebut diakhir tag <body>
$(“<p>What's cooking?</p>”).appendTo(“body”)
Selectors
Selectors allow you to manipulate HTML
elements as a group or as a single element
$(“#id”) element id
$(“p”) tag html
$(“p#id”) tag html dengan id
$(“.class”) css class
$(“p.class”) element <p> yang memiliki CSS class
$(“p:first”) element <p> yang pertama
$(“p:last”) element <p> yang terakhir
$(“p:even”) element <p> yang genap
$(“p:odd”) element<p> yang ganjil
$(“p a”) element <a> yang berada didalam element <p>
$(“p:eq(2)”) element <p> ketiga
$(“:not(p)”) semua element kecuali <p>
$(“p:hidden”) hanya element <p> yang hidden
$(“p:empty”) hanya element <p> yang tidak memiliki child element
$(“li:has(ul)”) element <li> yang memiliki setidaknya 1 tag <ul>
$(“img”[alt]) element <img> yang memiliki atribut alt
$(“p , a , img”) element <p> , <a> dan <img>
Contoh Selectors (1)
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#choose").css("background-color","#B2E0FF");
});
</script>
</head>
<body>
<p id="choose">Who is your favourite:</p>
<ul>
<li>
Goofy
<ul>
<li>Goofy 1</li>
<li>Goofy 2</li>
</ul>
</li>
<li>Mickey</li> Try this :
<li>Pluto</li> Coba highlight Tulisan Goofy, Goofy 1 dan
</ul> Goofy 2 dengan mengganti selector yang
</body>
</html> berwarna merah (3 selector yang berbeda)
Contoh Selectors (2) Stripes Table
<body>
<html> <table>
<head> <tr>
<th>Year</th>
<title>Zebra Stripes!</title>
<th>Make</th>
<script type="text/javascript" <th>Model</th>
src="jquery.js"></script> </tr>
<script type="text/javascript"> <tr>
$(document).ready(function(){ <td>1997</td>
<td>Chrysler</td>
$("table tr:odd").addClass("striped"); <td>Jeep Wrangler Sahara</td>
}); </tr>
</script> <tr>
<style> <td>2000</td>
table, td, tr, th{ <td>Chrysler</td>
<td>Jeep Wrangler Sahara</td>
border: 1px black solid; </tr>
} <tr>
table { <td>2005</td>
border-collapse: collapse; <td>Chrysler</td>
<td>Jeep Wrangler Unlimited</td>
}
</tr>
tr.striped { <tr>
background-color: coral; <td>2007</td>
} <td>Dodge</td>
</style> <td>Caliber R/T</td>
</tr>
</head> </table>
</body>
</html>
Selector Form
Masalah:
Bagaimana cara mengambil element form
berdasarkan atribut tipe.
Solusi :
JQuery Function
Digunakan pada selector atau Object JQuery.
Hampir semua mengembalikan object
JQuery sehingga banyak aksi / perintah yang
dapat dilakukan dalam 1 baris.
Satu fungsi dapat digunakan untuk
melakukan aksi / perintah yang berbeda
tergantung jenis dan jumlah paramater.
Useful JQuery Function
.each() iterate over the set Fungsi lengkap bisa dibaca di
.size() number of elements in set JQuery Cheat Sheet 1.4
.end() reverts to the previous set
.get(n) get just the nth element (0 based)
.eq(n) get just the nth element (0 based) also .lt(n) & .gt(n)
.slice(n,m) gets only nth to (m-1)th elements
.not(‘p’) don’t include ‘p’ elements in set
.add(‘p’) add <p> elements to set
.remove() removes all the elements from the page DOM
.empty() removes the contents of all the elements
.filter(fn/sel) selects elements where the func returns true or sel
.find(selector) selects elements meeting the selector criteria
.parent() returns the parent of each element in set
.children() returns all the children of each element in set
.next() gets next element of each element in set
.prev() gets previous element of each element in set
.siblings() gets all the siblings of the current element
Contoh JQuery Function
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("li:odd").prepend("<span>Changed</span>").css({background:"red"});
});
</script>
</head>
<body>
<ul>
<li>
First item
</li>
<li>
Second item
</li>
<li>
Third item
</li>
</ul>
</body>
</html>
Penjelasan Contoh
.prepend(‘<span>Changed</span>’)
.css({background:”red”})
Contoh selector Form & Function
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("span.none").click(
function(){
$(this).siblings(":checkbox").removeAttr("checked");
}
);
$("span.all").click(
function(){
$(this).siblings(":checkbox").attr("checked","checked");
}
);
});
</script>
</head>
<body>
<div>
<span class="all">Select All</span>
<span class="none">Select None</span>
<input name="chk1" type="checkbox"/>
<input name="chk2" type="checkbox"/>
<input name="chk3" type="checkbox"/>
</div>
<div>
<span class="all">Select All</span>
<span class="none">Select None</span>
<input name="chk4" type="checkbox"/>
<input name="chk5" type="checkbox"/>
<input name="chk6" type="checkbox"/>
</div>
</body>
</html>
Event
Pada dasarnya Event di JQuery sama dengan Event di JavaScript.
Syntax :
$("<selector>").<function_name>(function(){
//kode anda
});
Browser Events [.resize(), .error(), .scroll()]
Document Events [.load(), ready(), .unload()]
Event Handler Attachment [.bind(), .unbind()]
Event Object [event.currentTarget, event.data]
Form Events [.blur(), .focus(), .change(), .submit()]
Keyboard Events [.keyPress(), keyDown(), keyUp()]
Mouse Events [.click(), dblclick(), hover(), .mouseleave(),
.mousemove(), .toogle()]
http://api.jquery.com/category/events/
Contoh Mouse Event
<html> </script>
<head> </head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
<body>
$(document).ready(function(){
<button type="button"
$("button#butHighlight").hover(function(){
id="butHighlight">highlight</button>
if($("p").css("background-color") != "yellow")
<button type="button"
$("p").css("background-color","yellow");
id="butResize">Resize</button>
else
<!-- Jika height salah satu <p> dirubah, height
$("p").css("background-color","white");
mana yang dirubah? -->
});
<p>This is a paragraph.</p>
$("button#butResize").click(function(){
<p>This is another paragraph.</p>
if($("p").height() != 100){ </body>
$("p").height(100);
}else{ </html>
$("p").height(20);
}
});
});
Effect (1) Hide, Show, Toggle
Syntax :
$(selector).hide(speed,callback)
$(selector).show(speed,callback)
$(selector).toggle(speed,callback)
Speed parameter memiliki value slow, fast,
normal atau nilai pasti (dalam milliseconds)
Effect (2) slide, fade , animate
$(selector).slideDown(speed,callback)
$(selector).slideUp(speed,callback)
$(selector).slideToggle(speed,callback)
$(selector).fadeIn(speed,callback)
$(selector).fadeOut(speed,callback)
$(selector).fadeTo(speed,opacity,callback)
$(selector).animate({params},speed,easing,callback)
$(selector).stop();
Parameter :
opacity : Nilai transparansi 0 s/d 1
params : merubah css, mis : {height:50; width:50}
easing: membutuhkan tambahan plug-in http://gsgd.co.uk/sandbox/jquery/easing/
Contoh Effect (1)
<html>
<head>
<title>jQuery Effect 1</title>
<script type="text/javascript" src="jquery.js"/>
<script type="text/javascript">
$(document).ready(function(){
$("button.tb").click(
function(){
$("p").toggle();
}
);
$("#p1").click(function(){
$(this).hide();
});
$("#p2").click(function(){
$(this).fadeOut();
});
$("#p3").click(function(){
$(this).slideUp();
});
});
</script>
</head>
<body>
<button class="tb">Toggle Button</button>
<p id="p1"> This is paragraph with hide effect</p>
<p id="p2"> This is paragraph with fadeOut effect</p>
<p id="p3"> This is paragraph with slideUp effect</p>
</body>
</html>
Contoh Effect (2)
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#start").click(function(){
$("#box").animate({height:300},"slow");
$("#box").animate({width:300},"slow");
$("#box").animate({height:100},"slow");
$("#box").animate({width:100},"slow");
});
});
</script>
</head>
<body>
<p><a href="#" id="start">Start Animation</a></p>
<div id="box"
style="background:#98bf21;height:100px;width:100px;position:relat
ive">
</div>
</body>
Callback
Kasus :
Setiap Effect memiliki kecepatan yang berbeda-beda
yang dapat diatur secara custom.
Code JS dieksekuasi secara berurutan
Akibatnya :
Statement yang dijalankan setelah animasi dapat
menimbulkan error atau konflik halaman karena
animasi belum diimplement dengan sempurna
Solusi dari masalah ini adalah menggunakan Callback
The callback parameter is the name of a function to be executed
after the effect function completes.
WRONG (Without Callback)
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").hide(2000);
alert("The paragraph is now hidden");
});
});
</script>
</head>
<body>
<button type="button">Hide</button>
<p>This is a paragraph with little content.</p>
</body>
</html>
CORRECT (With Callback)
Gunakan callback untuk menjamin alert akan
dijalankan setelah animasi selesai.
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").hide(2000,my_alert);
});
});
function my_alert()
{
alert("The pagraph is now hidden");
}
</script>
Latihan
Buatlah Sebuah halaman web menggunakan HTML + CSS + jQuery
seperti gambar dibawah ini.
Jika user melakukan Mouse Over terhadap kotak-kotak kecil maka kotak
yang berwarna hitam akan berubah warna sesuai warna kotak kecil
tersebut.
That’s all for Today !
Thank you, any question ?