Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    Regular Coder
    Join Date
    Feb 2009
    Posts
    121
    Thanks
    7
    Thanked 0 Times in 0 Posts

    How to display words in red and green

    Hi,
    I have a long paragraph and I have been asked to display words in red and green in such a way that that fist word should be red, 2nd word should be green, 3rd word should be red and 4th word should be green and so on…
    For example: this is just a sample.

    Thank you for your participation.

    Jquery or JavaScript will do.

    Thanks.

  • #2
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    Try this.

    Code:
    <!DOCTYPE html>
    <head>
      <title>Untitled Document</title>
      <script type="text/javascript">
      (function($){
        $.colorChanger = function(o) {
          var i,j,t,e,n=1,c,k=[],r='red',g='green';
          if(o.substr(0,1) == ".") {
            e = document.getElementsByTagName('*');
            for(i=0;i<e.length;i++) {
              if(e[i].className == o.substr(1)) {
                t = e[i].innerHTML.split(' ');
                for(j=0;j<t.length;j++) {
                  if(n==1) {c=r;n=2;} else {c=g;n=1;}
                  k[j] = "<font color=\""+c+"\">"+t[j]+"</font>";
                }
                e[i].innerHTML = k.join(' ');
                n=1;
              }
            }
          } else if(o.substr(0,1) == "#") {
            e = document.getElementById(o.substr(1));
            t = e.innerHTML.split(' ');
            for(i=0;i<t.length;i++) {
              if(n==1) {c=r;n=2;} else {c=g;n=1;}
              k[i] = "<font color=\""+c+"\">"+t[i]+"</font>";
            }
            e.innerHTML = k.join(' ');
            n=1;
          }
        };
      })(window);
    
      window.onload=(function(){
        colorChanger('.demo'); // Use a dot (.) at the start for classes or a hash (#) for id's
      });
      </script>
    </head>
    <body>
    <div class="demo">Thank you for your participation.</div>
    <div class="demo">Thank you for your participation.</div>
    </body>
    </html>
    Last edited by DJCMBear; 12-24-2010 at 05:58 PM.
    Official BinPress hand picked coder.
    For anyone worried about SQL injection go have a look at my small yet powerful script here.
    Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
    I am 1 of 65,608 people to get a Pebble Watch :P

  • #3
    Senior Coder
    Join Date
    Mar 2005
    Location
    Portsmouth UK
    Posts
    4,533
    Thanks
    3
    Thanked 512 Times in 499 Posts
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    <style type="text/css">
    /*<![CDATA[*/
    .color1 {
     color:red;
    }
    
    .color2 {
     color:green;font-Size:20px;
    }
    
    /*]]>*/
    </style></head>
    
    <body>
    <div id="tst" >
    Thank you for your participation.
    <br />
    
    Thank you for your participation.
    </div>
    <script type="text/javascript">
    /*<![CDATA[*/
    
    function zxcWords(n){
     for(var nu=n.childNodes.length,txt,rn,s,nn,z0a,z0=0;z0<nu;z0++){
      txt=n.firstChild.data;
      rn=n.removeChild(n.firstChild);
      if(rn.nodeType==3){
       var s=txt.split(' ');
       for(z0a=0;z0a<s.length;z0a++) {
        nn=document.createElement('A');
        nn.className='zxc';
        nn.appendChild(document.createTextNode(s[z0a]));
        n.appendChild(nn);
        n.appendChild(document.createTextNode(' '));
       }
      }
      else {
       zxcWords(rn);
       n.appendChild(rn);
      }
     }
    }
    
    function zxcByClassName(nme,el,tag){
     if (typeof(el)=='string') el=document.getElementById(el);
     el=el||document;
     for (var tag=tag||'*',reg=new RegExp('\\b'+nme+'\\b'),els=el.getElementsByTagName(tag),ary=[],z0=0; z0<els.length;z0++){
      if(reg.test(els[z0].className)) ary.push(els[z0]);
     }
     return ary;
    }
    
    
    function ColorWords(o){
     var obj=document.getElementById(o.ID);
     zxcWords(obj);
     var words=zxcByClassName('zxc',obj,'A');
     for (var cnt=0,z0=0;z0<words.length;z0++){
      if (words[z0].innerHTML){
       words[z0].className=o.ClassNames[cnt%o.ClassNames.length==0?0:1];
       cnt++;
      }
     }
    }
    
    ColorWords({
     ID:'tst',
     ClassNames:['color1','color2']
    });
    /*]]>*/
    </script>
    
    </body>
    
    </html>
    Vic

    God Loves You and will never love you less.

    http://www.vicsjavascripts.org/Home.htm

    If my post has been useful please donate to http://www.operationsmile.org.uk/

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,298
    Thanks
    203
    Thanked 2,561 Times in 2,539 Posts
    Or rather shorter:-

    Code:
    <script type = "text/javascript">
    var txt = "Thank you for your valuable participation. We really appreciate it."
    txt = txt.replace(/\s{2,}/g," ");  // Replace multiple spaces with one space
    var txtsplit = txt.split(" ");
    var len = txtsplit.length;
    
    for (var i = 0; i<len; i++) {
    if (i%2 == 0) {
    txtsplit[i] = "<font color = 'red'>" + txtsplit[i] + "</font>"
    }
    else {
    txtsplit[i] = "<font color = 'green'>" + txtsplit[i] + "</font>"
    }
    }
    
    var newtext = txtsplit.join(" ");
    document.write(newtext);
    </script>

  • #5
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    What if the OP has all the text and mark-up already done, wouldn't changing the styles for all classes or the id's and not putting the text inside the javascript itself? just wondering if it's easier or not for the OP.
    Official BinPress hand picked coder.
    For anyone worried about SQL injection go have a look at my small yet powerful script here.
    Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
    I am 1 of 65,608 people to get a Pebble Watch :P

  • #6
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,145
    Thanks
    38
    Thanked 505 Times in 499 Posts
    Another solution to the problem the OP put on another forum (duplicated posts)
    See post #2 of : http://www.webdeveloper.com/forum/sh...d.php?t=240196

    Guess OP never got around to looking back there.
    Similar to post #4 here.

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,554
    Thanks
    80
    Thanked 4,620 Times in 4,583 Posts
    Couldn't help it. Even shorter:

    Code:
    <script type = "text/javascript">
    var txt = "Thank you for your valuable participation. We really appreciate it."
    // Replace (possibly multiple) spaces *AND TABS AND NEWLINES* with one space
    var words = txt.replace(/\s+/g," ").split(" ");  
    for (var i = 0; i < words.length; i++) {
        // font tag considered obsolete...use span instead:
        words[i] = '<span style="color: ' + (i%2==0?"red":"green") + ';">' 
                        + words[i] + "</span>"
    }
    document.write(words.join(" "));
    </script>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #8
    Regular Coder
    Join Date
    Feb 2009
    Posts
    121
    Thanks
    7
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by jmrker View Post
    Another solution to the problem the OP put on another forum (duplicated posts)
    See post #2 of : http://www.webdeveloper.com/forum/sh...d.php?t=240196

    Guess OP never got around to looking back there.
    Similar to post #4 here.
    Thank you very much every 1. Solution at http://www.webdeveloper.com/forum/sh...d.php?t=240196 works for me.

    Thanks

  • #9
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,298
    Thanks
    203
    Thanked 2,561 Times in 2,539 Posts
    Quote Originally Posted by asifakhtar View Post
    Thank you very much every 1. Solution at http://www.webdeveloper.com/forum/sh...d.php?t=240196 works for me.

    Thanks
    So we wasted our time!

  • #10
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    Hi all,

    I understand that the topic starter lost his interest to this theme. But I thought to myself that I can show another weird solution of the problem:

    Code:
    var txt = "Thank you for your valuable participation. We really appreciate it."
    
    var colors = ['red', 'green'];
    var i = 0;
    
    var result = txt.replace(/\w+/g, function($0)
    {
    	var result = '<span style="color: ' + colors[i] + '">' + $0 + '</span>';
    	i = (i + 1) % 2;
    	return result;
    });

  • #11
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,145
    Thanks
    38
    Thanked 505 Times in 499 Posts

    Thumbs up

    Quote Originally Posted by Philip M View Post
    So we wasted our time!
    Nah ... I just won one for a change. (see added 'rainbow' code at link)

  • #12
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,298
    Thanks
    203
    Thanked 2,561 Times in 2,539 Posts
    Quote Originally Posted by siberia-man View Post
    Hi all,

    I understand that the topic starter lost his interest to this theme. But I thought to myself that I can show another weird solution of the problem:

    Code:
    var txt = "Thank you for your valuable participation. We really appreciate it."
    
    var colors = ['red', 'green'];
    var i = 0;
    
    var result = txt.replace(/\w+/g, function($0)
    {
    	var result = '<span style="color: ' + colors[i] + '">' + $0 + '</span>';
    	i = (i + 1) % 2;
    	return result;
    
    });
    That strips the punctuation (and needs a space inserting between the words).


  •  

    Posting Permissions

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