Sunday, February 22, 2015

Belajar HTML5: Web Storage bag. 2

Mari kita lanjutkan belajar Web Storage pada HTML5. Nah, Contoh berikut menghitung berapa kali pengguna telah mengklik tombol. Dalam kode ini string nilai dikonversi menjadi jumlah untuk dapat meningkatkan counter:
<!DOCTYPE html>
<html>
<head>
<script>
function clickCounter()
{
if(typeof(Storage)!==”undefined”)
{
if (localStorage.clickcount)
{
localStorage.clickcount=Number(localStorage.clickcount)+1;
}
else
{
localStorage.clickcount=1;
}
document.getElementById(“result”).innerHTML=”You have clicked the button ” + localStorage.clickcount + ” time(s).”;
}
else
{
document.getElementById(“result”).innerHTML=”Sorry, your browser does not support web storage…”;
}
}
</script>
</head>
<body>
<p><button onclick=”clickCounter()” type=”button”>Click me!</button></p>
<div id=”result”></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).</p>
</body>
</html>
The sessionStorage Object
Obyek sessionStorage sama dengan objek localStorage, hanya saja ia menyimpan data hanya untuk satu sesi. Data tersebut dihapus saat pengguna menutup jendela browser.
Contoh berikut menghitung berapa kali pengguna telah mengklik tombol, dalam sesi saat ini:
<!DOCTYPE html>
<html>
<head>
<script>
function clickCounter()
{
if(typeof(Storage)!==”undefined”)
{
if (sessionStorage.clickcount)
{
sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
}
else
{
sessionStorage.clickcount=1;
}
document.getElementById(“result”).innerHTML=”You have clicked the button ” + sessionStorage.clickcount + ” time(s) in this session.”;
}
else
{
document.getElementById(“result”).innerHTML=”Sorry, your browser does not support web storage…”;
}
}
Try This: 4 Langkah Mudah Belajar Cara Membuat Website, Langsung Praktek! KLIK DI SINI!.
</script>
</head>
<body>
<p><button onclick=”clickCounter()” type=”button”>Click me!</button></p>
<div id=”result”></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter is reset.</p>
</body>
</html>

0 comments:

Post a Comment

 

© Copyright 2010 oleh HariZ| Powered By : Blogger