Frontend Development

Creating a color picker using jQuery

Submitted by Burned Designs, , Thread ID: 20922

Thread Closed

RE: Creating a color picker using jQuery

kahraman451
Newbie
Level:
0
Reputation:
0
Posts:
18
Likes:
0
Credits:
4
25-10-2017, 12:16 AM
#9
05-05-2016, 04:31 AM
BurnedDesigns Wrote:
This will be a simple tutorial for using cookies and a color changer.

So before we get started on any jquery we have to set up the html for the simple color selector. (once advanced enough you can use this color picker Link


Code:
<span id="showBox">Show</span>
<div id="colorBox">
  <div class="red"></div>
  <div class="blue"></div>
  <div class="orange"></div>
  <div class="purple"></div>
</div>

That's it for the html portion of the color picker.

Now lets style that html so it looks pertty.


Code:
span#showBox{
background:#fff;
border:1px solid #ccc;
padding:5px 10px;
border-radius:4px;
cursor:pointer;
font-family:arial,sans-serif;
color:#333;
}

div#colorBox{
margin-top:10px;
background:#fff;
border:1px solid #ccc;
padding:10px;
width:65px;
display:none;
}

div#colorBox > div{
height:30px;
width:30px;
display:inline-block;
}

.red{
background:#c13333;
}

.blue{
background:#336184;
}

.orange{
background:#fd8a17;
}

.purple{
background:#4c3382;
}

Now that our color box looks more pertty than your own face lets start on the jquery because if you just copy and past the code above you wont see anything aside from the show button. This color changer does work with cookies so it saves per browser.

Code:
$(document).ready(function(){
$("#showBox").click(function(){
  $("#colorBox").slideToggle();
});

  $(".red").click(function(){
    $('#container').addClass('red');
    $('#container').removeClass('blue');
    $('#container').removeClass('orange');
    $('#container').removeClass('purple');
    $.cookie("mycookie","red",{expires:999});
  });
  
   $(".blue").click(function(){
    $('#container').addClass('blue');
    $('#container').removeClass('red');
    $('#container').removeClass('orange');
    $('#container').removeClass('purple');
    $.cookie("mycookie","blue",{expires:999});
  });

$(".orange").click(function(){
    $('#container').addClass('orange');
    $('#container').removeClass('red');
    $('#container').removeClass('blue');
    $('#container').removeClass('purple');
    $.cookie("mycookie","orange",{expires:999});
  });
  
  $(".purple").click(function(){
    $('#container').addClass('purple');
    $('#container').removeClass('red');
    $('#container').removeClass('orange');
    $('#container').removeClass('blue');
    $.cookie("mycookie","purple",{expires:999});
  });


  //Check if cookie exists
  if (typeof $.cookie('mycookie') === "undefined"){
  //no cookie
  } else {
  //cookie is there, do something
   $('#container').addClass($.cookie('mycookie'));
  }
});

very nice Smile

Users browsing this thread: 1 Guest(s)