www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: Assign colour to elements of an Array (letters)

  1. #1
    Join Date
    Nov 2013
    Posts
    17

    Smile Assign colour to elements of an Array (letters)

    Any idea how to make all odd letters appear in one colour and all even leters appear in other colour? For example string 'COLOUR' is converted to an array. And then displayed in a way that letters C L and U are of colour red and letters O O and R are of coulour black? Converting string to an array was easy and so is seperating odd from even letters trough for loop. But how to assign colour to individual letters? Any ideas are welcome!
    Thanx guys!

  2. #2
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    795
    Don't really need an array for this:

    index.html
    Code:
    <!DOCTYPE html>
    <html lang="en">
    	<head>
    		<meta charset="utf-8" />
    		<title>Alternate Colours</title>
    	</head>
    	<body>
    
    		<script type="text/javascript">
    
    			var
    				text = 'COLOUR, and some more text...',
    				i;
    
    			for (i = 0; i < text.length; ++i) {
    				document.write('<span style="color: #' + (i % 2 ? '000' : 'f00') + ';">' + text.charAt(i) + '</span>');
    			}
    
    		</script>
    
    	</body>
    </html>
    --------------

    An array version if it was absolutely necessary:

    index.html
    Code:
    <!DOCTYPE html>
    <html lang="en">
    	<head>
    		<meta charset="utf-8" />
    		<title>Alternate Colours</title>
    	</head>
    	<body>
    
    		<script type="text/javascript">
    
    			var
    				text = 'COLOUR, and some more text...',
    				i, j;
    
    			for (i = 0, j = text.split(''); i < j.length; ++i) {
    				document.write('<span style="color: #' + (i % 2 ? '000' : 'f00') + ';">' + j[i] + '</span>');
    			}
    
    		</script>
    
    	</body>
    </html>
    Last edited by bionoid; 11-17-2013 at 08:08 AM.
    JavaScript: Learn | Validate | Compact | bionoid

  3. #3
    Join Date
    Nov 2013
    Posts
    17
    Thanx man. The simpler the better! Array isn't required. It's just that I thought was the only way to do it. Thank you so much!
    Cheers

  4. #4
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,266
    With a variant to change the colour progressively
    Code:
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8" />
            <title>Alternate Colours</title>
        </head>
        <body>
            <script type="text/javascript">
                var
                    text = 'COLOUR, and some more text...',
                    i, j;
                for (i = 0, j = text.split(''); i < j.length; ++i) {
                    document.write('<span style="color:rgb(' + Math.round(255*i/j.length)+',0,'+Math.round(255*(1-i/j.length))+')">' + j[i] + '</span>');
                }
            </script>
        </body>
    </html>

  5. #5
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    795
    Beautiful... and I managed to suppress my urge to compete with you
    JavaScript: Learn | Validate | Compact | bionoid

  6. #6
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,266
    With the following application to count characters...

  7. #7
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    795
    OK, you knew I couldn't resist anyway...
    Here is an hour wasted just to get this stuff out of my head:

    index.html
    Code:
    <!DOCTYPE html>
    <html lang="en">
    	<head>
    		<meta charset="utf-8" />
    		<title>Alternate Colours</title>
    	</head>
    	<body style="background-color: #000;">
    
    		<pre id="Base" style="font-weight: bold;">
    			Assign colour to elements of an Array (letters)
    
    			Any idea how to make all odd letters appear in one colour and all even leters appear in other colour?
    			For example string 'COLOUR' is converted to an array.
    			And then displayed in a way that letters C L and U are of colour red and letters O O and R are of coulour black?
    			Converting string to an array was easy and so is seperating odd from even letters trough for loop.
    			But how to assign colour to individual letters? Any ideas are welcome!
    			Thanx guys!
    
    			- bionoid
    		</pre>
    
    		<script type="text/javascript">
    
    			(function(id)
    			{
    				'use strict';
    
    				var
    					base = document.getElementById(id), text,
    					cur  = 0,
    					col  = [0, 0, 0, 0];
    
    				text = base.innerHTML;
    
    				function getRGB(a)
    				{
    					return [(a >> 16) & 255, (a >> 8) & 255, a & 255];
    				}
    				function getDiff(a, b)
    				{
    					a = getRGB(a);
    					b = getRGB(b);
    					return [
    						b[0] - ((b[0] - a[0]) * cur),
    						b[1] - ((b[1] - a[1]) * cur),
    						b[2] - ((b[2] - a[2]) * cur)
    					];
    				}
    				setInterval(function()
    				{
    					var i, j, k, a, b;
    
    					if ((cur -= 0.05) <= 0) {cur = 1;
    						col[0] = col[1]; col[1] = col[3]; col[2] = col[3];
    						col[3] = (((Math.random() * 256) | 0) << 16) + (((Math.random() * 256) | 0) << 8) + ((Math.random() * 256) | 0);
    					}
    
    					base.innerHTML = '';
    					for (i = 0, a = getDiff(col[0], col[1]), b = getDiff(col[2], col[3]); i < text.length; ++i) {
    						k = i / text.length;
    						j = base.appendChild(document.createElement('span'));
    						j.innerHTML = text.charAt(i);
    						j.style.color = 'rgb(' + ((a[0] + ((b[0] - a[0]) * k)) | 0) + ',' + ((a[1] + ((b[1] - a[1]) * k)) | 0) + ',' + ((a[2] + ((b[2] - a[2]) * k)) | 0) + ')';
    					}
    
    				}, 50);
    			}
    			('Base'));
    
    		</script>
    
    	</body>
    </html>
    Last edited by bionoid; 11-17-2013 at 11:50 AM.
    JavaScript: Learn | Validate | Compact | bionoid

  8. #8
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,648
    Quote Originally Posted by bionoid View Post
    ok, you knew i couldn't resist anyway...
    :d:d:d
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  9. #9
    Join Date
    Nov 2013
    Posts
    17
    Can any of you brilliant JS minds (and I really mean that!) give me advice how to make textbox accept letters only. I could do that using ascii code range (that's what I did with number field), however I need suppport for non english UTF8 characters like Ć Č Š Đ Ž. Here is the form: http://alenmikic.com/Validacija.html
    You can check JS code it's all in html document.
    Thank you!

  10. #10
    Join Date
    Nov 2013
    Posts
    17
    I need first to boxes above email to accept letter only.

  11. #11
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,266
    It's an other question, but shortly with an onkeyup, replace the textarea value with something like :

    Code:
    txaNewValue=txaValue.replace(/[^a-zA-ZĆČŠĐŽ]+/g,'')
    This regular expression replace all characters (one or more characters the plus sign - in many places the g) which are not (the ^) in the list (a-z for lower case letters - add ĆČŠĐŽ with this case A-Z - for upper case letters). Then you have probably to add spaces, digits, points, hyphen (with an antislash), at sign or other underscore...
    Last edited by 007Julien; 11-21-2013 at 07:37 AM.

  12. #12
    Join Date
    Nov 2013
    Posts
    17
    Thak you. I will do that. :-)

  13. #13
    Join Date
    Sep 2007
    Location
    istanbul
    Posts
    315
    Code:
      
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8" />
            <title>Alternate Colours</title>
        </head>
        <body>
    <div id="sevinmek" style="border:8px solid #596;">
    "İnşirâh" açılmak, genişlemek, sevinmek manalarına gelir. Duhâ sûresinden sonra Mekke'de inmiştir. 8 (sekiz) âyettir. Bu sûrede Peygamberimizin, çocukluğunda risalete hazırlamak üzere kalbinin açılıp arıtılmasından söz edilmektedir. Ayrıca, onun getirdiği dindeki kolaylıklara dikkat çekilerek Allah'a şükretmeye teşvik edilmektedir.
    
    Rahmân ve Rahîm (olan) Allah'ın adıyla.
    1. Biz senin göğsünü açıp genişletmedik mi?
    2. Yükünü senden alıp atmadık mı?
    3. O senin belini büken yükü.
    4. Senin şânını ve ününü yüceltmedik mi?
    5. Elbette zorluğun yanında bir kolaylık vardır.
    6. Gerçekten, zorlukla beraber bir kolaylık daha vardır.
    7. Boş kaldın mı hemen (başka) işe koyul,
    8. Yalnız Rabbine yönel ve yalvar.
    </div>
    <div id="numara"></div>
            <script type="text/javascript">
    // http://www.webdeveloper.com/forum/showthread.php?286607-Assign-colour-to-elements-of-an-Array-%28letters%29
    var el=document.getElementById('sevinmek');
    var text= el.innerHTML;
    // alert( text.split('').length );
    var A=[];
    var i, j, n=999, r, s=''; // n=596 
    for (i = 0, j = text.split(''); i < j.length; ++i) {
      if(n<10) { r ='00'+n;}
      if(n>10 && n<100) { r ='0'+n;}
      if(n>99 && n<1000) { r= ''+n;}  //  if(n>99 && n<597) { r= ''+n;}
      s+='<span style="font-size:24px; color:#' +r+'">' + j[i] + '</span>'; n= n-8; // n= n-94;
    if(n<1) {n=999; }   // if(n<1) {n=596; }
    A[A.length]=r;
    }
    //alert(A);
    
    el.innerHTML = s;
    
    var nu= document.getElementById('numara');
    // nu.innerHTML=A;
    
            </script>
        </body>
    </html>
    Bismillahirrahmanirrahîm
    Hamd, Âlemlerin Rabbi, Rahmân, Rahîm, hesap ve ceza gününün (ahiret gününün) maliki Allah'a mahsustur. (Allahım!) Yalnız sana ibadet ederiz ve yalnız senden yardım dileriz. Bizi doğru yola, kendilerine nimet verdiklerinin yoluna ilet; gazaba uğrayanların ve sapıklarınkine değil.

  14. #14
    Join Date
    Nov 2013
    Posts
    17
    Is there a any way to use for loop and fontcolor() method to paint red every other letter in a word? Like
    if (a[i] % 2 != 0) {
    something.fontcolor("red");
    ....
    This is what I tried...

    var s='First JavaScript string.';
    var c=' This is second text.';
    var c=s.concat(c);

    for(i=0;i<c.length;i++) {

    if(i % 2 != 0) {


    c[i].fontcolor("red");

    }

    document.write(c[i]);
    }

  15. #15
    Join Date
    Sep 2007
    Location
    istanbul
    Posts
    315
    Code:
      
    <script type="text/javascript">
    // http://www.w3schools.com/jsref/jsref_fontcolor.asp
    /*
    The fontcolor() method is used to display a string in a specified color.
    
    This method returns the string embedded in the <font> tag, like this:
    
    <font color="colorvalue">string</font>
    
    The <font> tag is not supported in HTML5. Use CSS instead.
    */
    // http://www.webdeveloper.com/forum/showthread.php?286607-Assign-colour-to-elements-of-an-Array-%28letters%29
    
    
    var s='First JavaScript string.';
    var b=' This is second text.';
    var c= s.concat(b).split('');
    
    for(i=0;i<c.length;i++) {
    
    if(i % 2 != 0) {  c[i]= c[i].fontcolor('red');  }
    
     document.write(c[i]);
    } 
    
    </script>
    Code:
      
    <script type="text/javascript">
    // http://www.w3schools.com/jsref/jsref_fontcolor.asp
    /*
    The fontcolor() method is used to display a string in a specified color.
    
    This method returns the string embedded in the <font> tag, like this:
    
    <font color="colorvalue">string</font>
    
    The <font> tag is not supported in HTML5. Use CSS instead.
    */
    // http://www.webdeveloper.com/forum/showthread.php?286607-Assign-colour-to-elements-of-an-Array-%28letters%29
    
    
    var s='First JavaScript string.';
    var b=' This is second text.';
    
    var c= s.concat(b);
    
    var str='';
    for(i=0;i<c.length;i++) {
    if(i % 2 == 0) { str += c[i]; }
    if(i % 2 != 0) {  str +=   c[i].fontcolor('red');  }
     
    } 
    
    document.write(str);
    
    </script>
    Last edited by Ayşe; 11-29-2013 at 07:23 AM.
    Bismillahirrahmanirrahîm
    Hamd, Âlemlerin Rabbi, Rahmân, Rahîm, hesap ve ceza gününün (ahiret gününün) maliki Allah'a mahsustur. (Allahım!) Yalnız sana ibadet ederiz ve yalnız senden yardım dileriz. Bizi doğru yola, kendilerine nimet verdiklerinin yoluna ilet; gazaba uğrayanların ve sapıklarınkine değil.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles