Problem with a ".click" event in jQ


#1

Hi!

Been studying like mad JS and jQ past month and just returned to fCC. Currently I’m in the process of making the random quote machine. I would like to ask You about my “.click” event: I know it can be done by other means but I want to be able to click on button and it will change bg color and text color in my doc. I wrote a rather good function but it only changes the colors once. How can it be rebuilt to change colors with every click? Here is the code:

‘$(document).ready(function(){
var colors = [’#16a085’, ‘#27ae60’, ‘#2c3e50’, ‘#f39c12’, ‘#e74c3c’, ‘#9b59b6’, ‘#FB6964’, ‘#342224’, ‘#472E32’, ‘#BDBB99’, ‘#77B1A9’, ‘#73A857’];

var randomColors = Math.floor(Math.random() * colors.length);

$(‘button’).on(‘click’,function(){
$(‘body, .btn’).css(‘background-color’, colors[randomColors]);
$(’#quotetext’).css(‘color’, colors[randomColors]);
});
});’

Note: I used only colors from example quote machine (they are nice), rest is my own :wink:
Note 2: Problem is that jQ probably sets new classes (or something) for css and refuses to do it again because there already are classes (set by first click event).


#2

Move this line:

var randomColors = Math.floor(Math.random() * colors.length);

into your button click function so it generates a new random number on every click.

$("button").on("click", function() {
  var randomColors = Math.floor(Math.random() * colors.length);
  $("body, .btn").css("background-color", colors[randomColors]);
  $("#quotetext").css("color", colors[randomColors]);
});

#3

Thanks a lot! :grin: