Search code examples
javascriptjquerycssrandomjquery-data

Assign a random background.color to objects with random ID


JSFIDDLE

I have created a button where a "person" is created every time you click on it. The person has a random ID (not a unique, I know). The next step for is to assign each of the people a random background color when they are created.

What I've accomplished so far is that every time a new person is created, all of the people changes their color:

$('#BtnCreatePerson').click(function(){
 var sPersonName = $('#PersonName').val();
 var sPersonLastName = $('#PersonLastName').val();
 var sPersonAge = $('#PersonAge').val();
 var sPersonGender = $('#PersonGender').val();
 var sColor = GetMeARandomColor();

 var iRandomId = GetRandomNumber(999999, 99999999999);

 var iDivPersonId = $(this).attr('id');
 $('.Person').data('current-elem-id', iDivPersonId, oPerson);

 var oPerson = new Person();
 oPerson.setId(iRandomId);
 aPeople.push(oPerson);
 console.dir(aPeople);


$('.PersonContainer').append('<div id="'+iRandomId+'" class="Person" title="'+sPersonName+'" ></div>')
$('.Person').data('current-elem-id', iDivPersonId, oPerson).css('background-color', sColor);

$('.Person').draggable();                     

});

The random color function:

function GetMeARandomColor()
{
var aEverything = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
var sTheColor = "#";
for(i=0; i < 6; i++)
{
   iRandomNumber = Math.floor(Math.random()* 16);
   sTheColor += aEverything[iRandomNumber];
   //console.log(sTheColor);
}  
return sTheColor;
}

You can check the whole code here: http://jsfiddle.net/Adnaves/fVtVL/

The new person should have a random color, and that color should never change again. I hope that you can help me to get it working, but also to understanding how.


Solution

  • Is it because you're referring to the new person as class .person rather than by id? So it changes the color for all person divs, not just the newly created one?

    Change

    $('.Person').data('current-elem-id', iDivPersonId, oPerson).css('background-color', sColor);
    

    to

    $('#'+iRandomId).data('current-elem-id', iDivPersonId, oPerson).css('background-color', sColor);
    

    This seems to work: http://jsfiddle.net/fVtVL/6/