yas17
yas17

Reputation: 421

use a variable in jQuery css

I want do this

$.fn.randomColor=function (cssSelect) {
  var color='RGB(' + rand(0, 255) + ',' + rand(0, 255) + ',' + rand(0, 255) + ')';
  $(this).css({cssSelect:color }); //error
  return this;
};

I want use cssSelect variable in css() function of jQuery

Upvotes: 0

Views: 42

Answers (1)

Chris Happy
Chris Happy

Reputation: 7305

Use the other form of .css().

$.fn.randomColor=function (cssSelect) {
    var color='RGB(' + rand(0, 255) + ',' + rand(0, 255) + ',' + rand(0, 255) + ')';
     $(this).css(cssSelect, color);
    return this;
};

jQuery.fn.randomColor=function (cssSelect) {
    var color='RGB(' + rand(0, 255) + ',' + rand(0, 255) + ',' + rand(0, 255) + ')';
     $(this).css(cssSelect, color);
    return this;
};

jQuery('div').on('click', function() {
  jQuery(this).randomColor('background');
});

function rand(min, max) {
  return Math.floor((Math.random() * max) + min);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Click me!</div>

Upvotes: 1

Related Questions