Utsav Utsav - 1 year ago 71
jQuery Question

Setting font-size with random value using jQuery?

When returning a fixed value, font-size is changing fine:

$wordElement.css('font-size', function() {
return '3vw';

But when trying to return a random value like this:

$wordElement.css('font-size', function() {
return '\'' + Math.ceil((cssRandom * 3) + 1) + 'vw\'';

It does not work.
What's wrong here? And how do I set font-size to random value?

Answer Source

Remove unnecessary escape and quotes surrounding Math.ceil call. You can use $.now() .slice() to retrieve a "random" numeric value

var cssRandom = String($.now()).slice(-1);
$("div").css("font-size", function() {
   return Math.ceil((cssRandom * 3) + 1) + "vw";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download