Showing posts with label Java script. Show all posts
Showing posts with label Java script. Show all posts

Monday, August 26, 2013

Get a random color in JavaScript

Computer can understand only hexadecimal color code.

As a science student, you might be known.
Converting a base(x) number to base(n) number.

Same logic we are going to use. In JavaScript we have base conversions.

Math.random() will return a float number. Convert this number to integer as well string too.
While your converting string pass "16" parameter to toString(16) function. So, this way it converts a string to base(16) number.

 Solution :  
1. '#'+Math.floor((Math.random()*100000000)).toString(16)
2.  '#'+(( 1<<24)*Math.random()|0).toString(16)

This function will hep you to generate number of colors as you given input number

var getRandomColors = function(no){
    no = no || 0;
    no = parseInt(no,10);
    var i=0,arr=[];
    do{
        arr.push( "#"+(( 1<<24)*Math.random()|0).toString(16) );
        i++;
    }while (i < no);
    return arr;
}

Friday, October 28, 2011

Easy way to read cookie and with out loop..

Assuming, reader know about what is cookie.
As of you know, document.cookie is java script key word and most of the times i use to write on OOP's.
let us code:

  1. var obj={};
  2. obj.c=document.cookie;
  3. //Define read cookie name:
    obj.cName = '__utmz';
  4. //split obj.c, this way:
    obj.c1 =obj.c.split(obj.cName+'=');
    // here am adding "=" to cookie name, because browser stores cookie and values as in format of string
    Ex: "TL=te:0; __utma=150635877.1168279805.1319048317.1319048317.1319822141.2; __utmb=150635877.3.10.1319822141; __utmc=150635877; __utmz=150635877.1319048317.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)"
  5. simple check an condition if obj.c1 > 1 then expected cookie exist other wise, dose not exist.
  6. if Exists:
    obj.data = obj.c1[1].split(';')[0]
  7. Finally obj.data is your cookie data.
In single line of code for reading cookie value is
function readcookie(cookiename){
var val = '';
try{
//if cookie present on the doc
              val = document.cookie.split(cookiename)[1].split('; ')[0].split('=')[1]
 }catch(e){
//cookie dose not present on the doc.
val = '';
}
return val;
}

var cookieVal = readcookie('cookiename');

Thank you.