Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

3/10/2013

Cool HTML5 color slider with vanilla javascript (chrome only)

HTML5 is full of surprises. Here is a cool demo how to create custom color slider with only HTML5 and javaScript. But before we dive into creating slider, there are some thing that needs to be sad about HTML5.

First, HTML5 is job in progress. It is not standardized yet. That leads us to one big issue - browser support. Before doing some actuall work be sure to test in all modern browsers.
Here is one great resource that can help:

http://caniuse.com/#compare=ie+5.5,ie+6,ie+7,ie+8,ie+9,ie+10

Next, HTML5 together with CSS3  is bringing new refreshment to 20 year old technology. Now HTML is not just a markup language, which we use to outline our document. It is a platform for creating powerfull web applications. Some of main changes includes new structural tags ( header, section,artice ...) that are semantically focused and closer to users and clients. Also, there are new application specific tags ( video,audio... ), new form  elements ( email,range,color...).

Let's see out example. First html:


<ol>

<li><input type = "range" value = "0" id = "r" min = "0" max = "255"></li> 
<li><input type = "range" value = "0" id = "g" min = "0" max = "255"></li>
<li><input type = "range" value = "0" id = "b" min = "0" max = "255"></li>

</ol>


Put this html snippet somewhere inside body.

Now javascript. Place script in external file or between script tags:

// lets use new dom selectors
var r = document.querySelectorAll("input")[0];
var g = document.querySelectorAll("input")[1];
var b = document.querySelectorAll("input")[2];

// and functionality
// adding change event ( which fires on value change of input elements ) to body
document.body.addEventListener("change",function(){
    document.body.style.background = "rgb("
    + [r.value,g.value,b.value].join(",") // join values of sliders and update background color
    + ")";
});

Now, when you move the slider, background color of your page shoud change also.

Happy Coding.

No comments:

Post a Comment