Buffalo Coder Buffalo Coder - 4 months ago 10
CSS Question

Naming and embedding functions in Jquery

I have been all through this. Trying to change the color of a button's background color to a random color on click. I can't figure out how to place my function in correct JQUERY format. Help please.


$( document ).ready(function getRandomColor() {
var randomColor = Math.floor(Math.random()*16777215).toString(16);
return randomColor;
});
});
$("button").click(function(){
$(this).css({'background-color':getRandomColor()});
});
});

Answer

Separate functions, begin string which set background-color with #. See colors

$(document).ready(function() {
  function getRandomColor() {
    var randomColor = Math.floor(Math.random() * 16777215).toString(16);
    return randomColor;
  }

  $("button").click(function() {
    $(this).css(
      'background-color', "#" + getRandomColor()
    );
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click</button>

Comments