28 Sep 2013

JQUERY Mengubah Background Color Secara Dinamis

Untuk mengubah background atau css ataupun kode secara runtime (tanpa reload halaman) diperlukan jq... thumbnail 1 summary
jquery-mark-light
Untuk mengubah background atau css ataupun kode secara runtime (tanpa reload halaman) diperlukan jquery, sekarang mari kita membuat kode mengubah background color pada halaman secara runtime.

1. Include
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
 2. CSS (membuat slider merah,biru,hijau)
<style>
#red, #green, #blue,#divnilai {
float: left;
clear: left;
width: 300px;
margin: 15px;
}
#swatch {
width: 120px;
height: 100px;
margin-top: 18px;
margin-left: 350px;
background-image: none;
}
#red .ui-slider-range { background: #ef2929; }
#red .ui-slider-handle { border-color: #ef2929; }
#green .ui-slider-range { background: #8ae234; }
#green .ui-slider-handle { border-color: #8ae234; }
#blue .ui-slider-range { background: #729fcf; }
#blue .ui-slider-handle { border-color: #729fcf; }
</style>
 3. Javascript
<script>
function hexFromRGB(r, g, b) {
var hex = [
r.toString( 16 ),
g.toString( 16 ),
b.toString( 16 )
];
$.each( hex, function( nr, val ) {
if ( val.length === 1 ) {
hex[ nr ] = "0" + val;
}
});
return hex.join( "" ).toUpperCase();
}
function refreshSwatch() {
var red = $( "#red" ).slider( "value" ),
green = $( "#green" ).slider( "value" ),
blue = $( "#blue" ).slider( "value" ),
hex = hexFromRGB( red, green, blue );
$( "body" ).css( "background-color", "#" + hex );
$('input[name=nilai]').val("#" + hex);
$('#kode').val("body{background-color: # " + hex +";}");

}
$(function() {
$( "#red, #green, #blue" ).slider({
orientation: "horizontal",
range: "min",
max: 255,
value: 127,
slide: refreshSwatch,
change: refreshSwatch
});
$( "#red" ).slider( "value", 255 );
$( "#green" ).slider( "value", 140 );
$( "#blue" ).slider( "value", 60 );
});
</script>
4. HTML Tag ( Untuk outputnya )
<div id="red"></div>
<div id="green"></div>
<div id="blue"></div>
<div id="divnilai">
Nilai RGB<input type="text" name="nilai"><br>
<textarea id="kode"></textarea>
</div>

Penjelasan :
Jadi, ada 3 slider merah,hijau,biru saat digeser lalu dijoinkan nilai hex tersebut (nilai hex merah,hijau,biru) lalu akan mendapatkan nilai RGB (fungsi hexFromRGB)