Nicolas Bocquel
Nicolas Bocquel

Reputation: 101

Jquery, multiple CSS properties in variables

I would like to have, with Jquery, multiples css properties in variables. This code doesn't work :

var deco = {"text-decoration":"none"};
var bak = {"background-color":"cyan"};


$("a").css( deco , bak );

What is wrong in my code ? Thanks. Nicolas.

Upvotes: 2

Views: 115

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

What's wrong is that you're calling the css function in a way it's not written to be called. The version accepting an object just accepts a single object.

You can combine your objects as you pass them in with $.extend:

$("a").css( $.extend( {}, deco , bak ) );

Example:

console.log("And...");
setTimeout(function() {
  var deco = {"text-decoration":"none"};
  var bak = {"background-color":"cyan"};
  $("a").css( $.extend( {}, deco , bak ) );
  console.log("...done");
}, 800);
<a href="http://example.com">Testing 1 2 3</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Side note: I'd strongly recommend using a class for that rather than inline styling, unless you have a strong, specific reason not to.

Upvotes: 4

Related Questions