Membuat Background berubah secara berulang.
Web Programming
Hallo, selamat pagi. Kali ini saya akan membagikan sebuah script yang bisa membuat background bisa berubah secara berurutan dengan javascript.
Langkah pertama
Persiapan HTML code nya. ini adalah contoh html codenya
<body id="body">
<h4 class="element"></h4>
<input class="kembali" type="button" style="display:none" value="Kembali ke index">
</body>
<h4 class="element"></h4>
<input class="kembali" type="button" style="display:none" value="Kembali ke index">
</body>
Langkah kedua
Persiapan CSS code nya. Ini adalah contoh css codenya
.color1{
background: grey;
color: black;
background-size:cover;
}
.color2{
background: red;
color: white;
background-size:cover;
}
.color3{
background: blue;
color: white;
background-size:cover;
}
.color4{
background: green;
color: white;
background-size:cover;
}
Catatan :background: grey;
color: black;
background-size:cover;
}
.color2{
background: red;
color: white;
background-size:cover;
}
.color3{
background: blue;
color: white;
background-size:cover;
}
.color4{
background: green;
color: white;
background-size:cover;
}
* .color1 , color2, color3, color4 bisa anda edit sekreatif mungkin. Ini hanyalah sebagai contoh.
** saya tambahkan syntax background-size: cover; agar ukuran background full
Langkah ketiga
Persiapan javascriptnya. Ini adalah contoh javascriptnya :
<script src="https://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
<script>
function changeColor(element, pos){
pos++;
if(pos > 4){
pos = 1;
}
console.log(pos);
element.addClass('bg' + pos, 1000);
// So previous classes get removed.
element.attr('class', 'bg' + pos);
setTimeout(function(){changeColor(element, pos)}, 1000);
}
changeColor($('#body'), 0);
</script>
Catatan<script>
function changeColor(element, pos){
pos++;
if(pos > 4){
pos = 1;
}
console.log(pos);
element.addClass('bg' + pos, 1000);
// So previous classes get removed.
element.attr('class', 'bg' + pos);
setTimeout(function(){changeColor(element, pos)}, 1000);
}
changeColor($('#body'), 0);
</script>
* Pada bagian changeColor($('#body'), 0 #body bisa diganti dengan elemen lain
Sekian tutorial dari saya. Bila ada pertanyaan, mohon komentar.
