0

In my JavaScript program I have randomly generated color for background by using Math.random(). Upon loading the page it's automatically generating random color. I have also created link CLICK HERE. When user click on link it should also generate background color for that I used Onclick function and added code to randomly generate color but when I click on link it's not generating. Every time I click on link it should generate random color. Can anyone correct me ?

code:

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        #para{
            text-align: center;
            font-size: 20px;
            color: white;
        }

        #link{
            text-align: center;
            font-size: 20px;
            }


    </style>
    <title>lab13</title>
    <script type="text/javascript">

        document.write('<br>'); document.write('<br>');
        document.write('<p id = "para">' + 'BACKGROUND-COLOR IS RANDOMLY GENERATED' + '</p>');



        function random_bg_color(){

        var rgbcolor;
        red = Math.floor(Math.random() * 250 + 0 );
        green = Math.floor(Math.random() * 250 + 0);
        blue = Math.floor(Math.random() * 250 + 0);

        rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
        document.body.style.background = rgbColor;

        document.write('<p id = "para">RGB(' + red + ', ' + green +  ', ' + blue + ')</p>');

        red = ("0" + red.toString(16)).substr(-2).toUpperCase();
        green = ("0" + green.toString(16)).substr(-2).toUpperCase();
        blue = ("0" + blue.toString(16)).substr(-2).toUpperCase();

        document.write("<p id = 'para'>HEX: #" + red + '' + green + '' + blue + '</p>');

        }

        random_bg_color();

        function randomize() { 
        random_bg_color();
        document.body.style.background = rgbColor;
        }


    </script>
</head>
<body>

    <a id="a1" href="#" onclick="randomize()"> CLICK TO RANDOM </a>

</body>
</html>

output:

enter image description here

pari
  • 89
  • 1
  • 12
  • 1
    You are generating a random color at runtime, where `random_bg_color()` is only being called once. You will have to re-call that method again within the `randomize()` method to generate a **new** random color and set it, i.e. `function randomize() { random_bg_color(); }` – Terry Oct 12 '17 at 18:55

7 Answers7

2

The issue is that randomize() was only setting the background color, not actually generating a new color. So the following randomize() will generate a new color AND will set the background color to that value.

It will be called on page load (the last line), and the onclick on the link will call this directly.

function randomize() {
  var rgbcolor;
  red = Math.floor(Math.random() * 250 + 0);
  green = Math.floor(Math.random() * 250 + 0);
  blue = Math.floor(Math.random() * 250 + 0);

  rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
  document.body.style.background = rgbColor;

  red = ("0" + red.toString(16)).substr(-2).toUpperCase();
  green = ("0" + green.toString(16)).substr(-2).toUpperCase();
  blue = ("0" + blue.toString(16)).substr(-2).toUpperCase();
}

randomize();
WOUNDEDStevenJones
  • 5,150
  • 6
  • 41
  • 53
  • 1
    You don't even need to set the background color again in `randomize()`, that has been taken care of in `random_bg_color()` ;) – Terry Oct 12 '17 at 18:57
  • Also note that RGB colors are 0-255, not just 0-250 (though this may be your intended functionality) – WOUNDEDStevenJones Oct 12 '17 at 19:02
1

As others have said, you must generate a new random value upon each click, but the code can be very much simpler than all the other answers.

Additionally, you seem to be learning JavaScript (and perhaps HTML too), so let's not pick up bad habits right from the start:

  • Don't use inline HTML event attributes (onclick, onmouseover, etc.). That is a technique that was used about 20 years ago back before we had standards and more robust ways of doing things. Unfortunately, is has become so ubiquitous and used so prolifically, that most people (including book authors) still use it when they shouldn't. There are many reasons not to use them and I've written about that here.
  • Don't use document.write() unless you are dynamically creating a new window and need to write content into it. Instead prepare HTML elements ahead of time to serve as output containers or create the new elements and inject them into the web page using modern standards (i.e. document.createElement() and element.appendChild()).
  • Don't use hyperlinks just because you need something for someone to click on. Hyperlinks are meant specifically for navigation, so don't use them unless you are actually navigating somewhere. Just about every HTML element supports a click event, so use a more benign element for custom click actions.
  • Specifying type=text/javascript and type=text/css on your <script> and <style> elements has not been needed for several years now. Those type values are the defaults for those elements.

Ok, with all that in mind, look how simple your task is using modern code:

#a1 { cursor:pointer; } /* Make div feel like a hyperlink */
<!DOCTYPE html>
<html>
<head>
    <title>lab13</title>
</head>
<body>

    <p id="para">BACKGROUND-COLOR IS RANDOMLY GENERATED</p>
    <!-- Use generic elements for custom click actions, not <a> elements: -->
    <div id="a1">CLICK TO RANDOM</div>
    <div id="output"></div>
    
    <!-- By placing the script at the end of the HTML, you can be sure
         that scanning for HTML elements will work.     -->
    <script>
      var link = document.getElementById("a1");
      var output = document.getElementById("output");
      // And when the link is clicked:
      link.addEventListener("click", getRandom);          
      
      function getRandom(){
        // 16777215 (decimal) == ffffff in hexidecimal
        var newColor = '#'+Math.floor(Math.random()*16777215).toString(16);
        
        // Convert hex to RGB:
        var rgbColor = newColor.replace('#','');
        var r = parseInt(rgbColor.substring(0,2), 16);
        var g = parseInt(rgbColor.substring(2,4), 16);
        var b = parseInt(rgbColor.substring(4,6), 16);
        var result = 'rgba(' + r + ',' + g + ',' + b + ')';
        
        document.body.style.backgroundColor = newColor;
        output.textContent = newColor + " - " + result;
      };
      
      // We want the background to get a random color as soon as the page loads
      // as well as when the link is clicked, so the function will be called right away      
      getRandom();  
    </script>
</body>
</html>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • I also need to show hexaCode and RGB color value on screen As shown in expected output. Do I need to create element for that ? – pari Oct 12 '17 at 19:38
  • You could. But, you could just concatenate the RGB value right next to the HEX value. – Scott Marcus Oct 12 '17 at 19:39
  • @ Scott It's requirement to create link for CLICK TO RANDOM – pari Oct 12 '17 at 19:55
  • @ Scott I want to display color value and hex value. Should I create P element ? – pari Oct 12 '17 at 20:03
  • @pari Well, you could just put the link back in as you originally had it, but that is wrong and you should let whomever is asking you to do it that way that using a hyperlink for this purpose is semantically incorrect and can have an adverse affect on users who rely on screen reader software. – Scott Marcus Oct 12 '17 at 20:14
  • @pari My answer does show the rgb and the hex value. No need to create any new elements. – Scott Marcus Oct 12 '17 at 20:14
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/156593/discussion-between-pari-and-scott-marcus). – pari Oct 12 '17 at 20:24
  • @pari See my updated answer that addresses your last comment. – Scott Marcus Oct 13 '17 at 02:00
0

Just need to put the function call in the right place!

function randomize() {
  random_bg_color();
  document.body.style.background = rgbColor;
}
Nick
  • 16,066
  • 3
  • 16
  • 32
0

You should call random_bg_color(); inside randomize function in order to regenerate new color each time.

yılmaz
  • 1,818
  • 13
  • 15
0

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
};

function randomize() {
  document.body.style.background = getRandomColor();
};
<a id="a1" href="#" onclick="randomize()"> CLICK HERE </a>
0

Just call random_bg_color() in the onclick.

function random_bg_color(){

        var rgbcolor;
        red = Math.floor(Math.random() * 250 + 0 );
        green = Math.floor(Math.random() * 250 + 0);
        blue = Math.floor(Math.random() * 250 + 0);

        rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
        document.body.style.background = rgbColor;


        red = ("0" + red.toString(16)).substr(-2).toUpperCase();
        green = ("0" + green.toString(16)).substr(-2).toUpperCase();
        blue = ("0" + blue.toString(16)).substr(-2).toUpperCase();


        }

        random_bg_color();
<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        #para{
            text-align: center;
            font-size: 20px;
            color: white;
        }

        #link{
            text-align: center;
            font-size: 20px;
            }


    </style>
    <title>lab13</title>
</head>
<body>

    <a id="a1" href="#" onclick="random_bg_color()"> CLICK HERE </a>

</body>
</html>
Juan
  • 6,125
  • 3
  • 30
  • 31
  • I updated code ... see above my expected output. Every time I click on link it should generate random color and text also. – pari Oct 12 '17 at 19:09
  • when I first time click on link it generate random color and link is gone. What should I do? – pari Oct 12 '17 at 19:23
0

The problem is that you are calling incorrect function.

OnClick you need to call function: random_bg_color

I fixed your snippet.

function random_bg_color() {

  var rgbcolor;
  red = Math.floor(Math.random() * 250 + 0);
  green = Math.floor(Math.random() * 250 + 0);
  blue = Math.floor(Math.random() * 250 + 0);

  rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
  document.body.style.background = rgbColor;


  red = ("0" + red.toString(16)).substr(-2).toUpperCase();
  green = ("0" + green.toString(16)).substr(-2).toUpperCase();
  blue = ("0" + blue.toString(16)).substr(-2).toUpperCase();


}

random_bg_color();
#para {
  text-align: center;
  font-size: 20px;
  color: white;
}

#link {
  text-align: center;
  font-size: 20px;
}
<a id="a1" href="#" onclick="random_bg_color()"> CLICK HERE </a>
  • I updated code ... see above my expected output. Every time I click on link it should generate random color and text also. – pari Oct 12 '17 at 19:05
  • when I first time click on link it generate random color and link is gone. What should I do? – pari Oct 12 '17 at 19:22