pari
pari

Reputation: 89

Generate random background color by clicking on link

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

Upvotes: 0

Views: 4048

Answers (7)

Scott Marcus
Scott Marcus

Reputation: 65835

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>

Upvotes: 1

WOUNDEDStevenJones
WOUNDEDStevenJones

Reputation: 5315

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();

Upvotes: 2

Gžegož Jurgo
Gžegož Jurgo

Reputation: 1

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>

Upvotes: 0

Juan
Juan

Reputation: 6383

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>

Upvotes: 0

Rostyslav Kuzmovych
Rostyslav Kuzmovych

Reputation: 241

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>

Upvotes: 0

yılmaz
yılmaz

Reputation: 1836

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

Upvotes: 0

Nick
Nick

Reputation: 16586

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

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

Upvotes: 0

Related Questions