1

So I have a script that generates a hex code, and changes the background. Here's the code

$(document).ready(function() {
$(document).keydown(function(e) {
  if (e.keyCode == '32') { 
     var color = "#" + Math.random().toString(16).slice(2, 8);
      document.write(color);
      document.body.style.backgroundColor = color;

    }
  });
});

The issue is when I press space, it only changes the color once, and I won't be able to press space again to generate another color without reloading the page. Here's a demo. Any ideas?

2 Answers2

3

Do not use document.write.

it will wipe your script so you should append it in body:

$(document.body).append(color);
document.body.style.backgroundColor = color;

or add a span and set its text:

$("span").text(color);

UPDATED JSBIN

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

http://jsfiddle.net/EVjaH/

$(document).ready(function(){

    $('body').on('keydown',function(e) {
              if (e.which == '32') {

                var color = "#" + Math.random().toString(16).slice(2, 8);
                $('body').css('background',color);


              }
            }); 

    });
bhavya_w
  • 9,186
  • 9
  • 29
  • 38